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 */
mbedtls_zeroize(void * v,size_t n)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 */
ssl_ep_len(const mbedtls_ssl_context * ssl)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  */
ssl_set_timer(mbedtls_ssl_context * ssl,uint32_t millisecs)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  */
ssl_check_timer(mbedtls_ssl_context * ssl)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  */
ssl_double_retransmit_timeout(mbedtls_ssl_context * ssl)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 
ssl_reset_retransmit_timeout(mbedtls_ssl_context * ssl)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)
ssl_session_copy(mbedtls_ssl_session * dst,const mbedtls_ssl_session * src)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)
ssl3_prf(const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)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)
tls1_prf(const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)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)
tls_prf_generic(mbedtls_md_type_t md_type,const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)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)
tls_prf_sha256(const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)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)
tls_prf_sha384(const unsigned char * secret,size_t slen,const char * label,const unsigned char * random,size_t rlen,unsigned char * dstbuf,size_t dlen)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 
mbedtls_ssl_derive_keys(mbedtls_ssl_context * ssl)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)
ssl_calc_verify_ssl(mbedtls_ssl_context * ssl,unsigned char hash[36])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)
ssl_calc_verify_tls(mbedtls_ssl_context * ssl,unsigned char hash[36])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)
ssl_calc_verify_tls_sha256(mbedtls_ssl_context * ssl,unsigned char hash[32])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)
ssl_calc_verify_tls_sha384(mbedtls_ssl_context * ssl,unsigned char hash[48])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)
mbedtls_ssl_psk_derive_premaster(mbedtls_ssl_context * ssl,mbedtls_key_exchange_type_t key_ex)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  */
ssl_mac(mbedtls_md_context_t * md_ctx,unsigned char * secret,unsigned char * buf,size_t len,unsigned char * ctr,int type)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  */
ssl_encrypt_buf(mbedtls_ssl_context * ssl)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 
ssl_decrypt_buf(mbedtls_ssl_context * ssl)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  */
ssl_compress_buf(mbedtls_ssl_context * ssl)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 
ssl_decompress_buf(mbedtls_ssl_context * ssl)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)
ssl_resend_hello_request(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_fetch_input(mbedtls_ssl_context * ssl,size_t nb_want)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  */
mbedtls_ssl_flush_output(mbedtls_ssl_context * ssl)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  */
ssl_flight_append(mbedtls_ssl_context * ssl)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  */
ssl_flight_free(mbedtls_ssl_flight_item * flight)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  */
ssl_swap_epochs(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_resend(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_recv_flight_completed(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_send_flight_completed(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_write_record(mbedtls_ssl_context * ssl)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  */
ssl_bitmask_set(unsigned char * mask,size_t offset,size_t len)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  */
ssl_bitmask_check(unsigned char * mask,size_t len)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  */
ssl_reassemble_dtls_handshake(mbedtls_ssl_context * ssl)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 
mbedtls_ssl_prepare_handshake_record(mbedtls_ssl_context * ssl)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 
mbedtls_ssl_update_handshake_status(mbedtls_ssl_context * ssl)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)
ssl_dtls_replay_reset(mbedtls_ssl_context * ssl)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 
ssl_load_six_bytes(unsigned char * buf)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  */
mbedtls_ssl_dtls_replay_check(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_dtls_replay_update(mbedtls_ssl_context * ssl)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  */
ssl_check_dtls_clihlo_cookie(mbedtls_ssl_cookie_write_t * f_cookie_write,mbedtls_ssl_cookie_check_t * f_cookie_check,void * p_cookie,const unsigned char * cli_id,size_t cli_id_len,const unsigned char * in,size_t in_len,unsigned char * obuf,size_t buf_len,size_t * olen)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  */
ssl_handle_possible_reconnect(mbedtls_ssl_context * ssl)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  */
ssl_parse_record_header(mbedtls_ssl_context * ssl)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  */
ssl_prepare_record_content(mbedtls_ssl_context * ssl)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  */
mbedtls_ssl_read_record(mbedtls_ssl_context * ssl)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 
mbedtls_ssl_read_record_layer(mbedtls_ssl_context * ssl)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 
mbedtls_ssl_handle_message_type(mbedtls_ssl_context * ssl)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 
mbedtls_ssl_send_fatal_handshake_failure(mbedtls_ssl_context * ssl)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 
mbedtls_ssl_send_alert_message(mbedtls_ssl_context * ssl,unsigned char level,unsigned char message)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)
mbedtls_ssl_write_certificate(mbedtls_ssl_context * ssl)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     {
4071         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4072         ssl->state++;
4073         return( 0 );
4074     }
4075 
4076     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4077     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4078 }
4079 
mbedtls_ssl_parse_certificate(mbedtls_ssl_context * ssl)4080 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4081 {
4082     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4083 
4084     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4085 
4086     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4087         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4088         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4089         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4090     {
4091         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4092         ssl->state++;
4093         return( 0 );
4094     }
4095 
4096     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4097     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4098 }
4099 #else
mbedtls_ssl_write_certificate(mbedtls_ssl_context * ssl)4100 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4101 {
4102     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4103     size_t i, n;
4104     const mbedtls_x509_crt *crt;
4105     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4106 
4107     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4108 
4109     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4110         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4111         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4112         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4113     {
4114         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4115         ssl->state++;
4116         return( 0 );
4117     }
4118 
4119 #if defined(MBEDTLS_SSL_CLI_C)
4120     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
4121     {
4122         if( ssl->client_auth == 0 )
4123         {
4124             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4125             ssl->state++;
4126             return( 0 );
4127         }
4128 
4129 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4130         /*
4131          * If using SSLv3 and got no cert, send an Alert message
4132          * (otherwise an empty Certificate message will be sent).
4133          */
4134         if( mbedtls_ssl_own_cert( ssl )  == NULL &&
4135             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4136         {
4137             ssl->out_msglen  = 2;
4138             ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4139             ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
4140             ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
4141 
4142             MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
4143             goto write_msg;
4144         }
4145 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4146     }
4147 #endif /* MBEDTLS_SSL_CLI_C */
4148 #if defined(MBEDTLS_SSL_SRV_C)
4149     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
4150     {
4151         if( mbedtls_ssl_own_cert( ssl ) == NULL )
4152         {
4153             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
4154             return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
4155         }
4156     }
4157 #endif
4158 
4159     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
4160 
4161     /*
4162      *     0  .  0    handshake type
4163      *     1  .  3    handshake length
4164      *     4  .  6    length of all certs
4165      *     7  .  9    length of cert. 1
4166      *    10  . n-1   peer certificate
4167      *     n  . n+2   length of cert. 2
4168      *    n+3 . ...   upper level cert, etc.
4169      */
4170     i = 7;
4171     crt = mbedtls_ssl_own_cert( ssl );
4172 
4173     while( crt != NULL )
4174     {
4175         n = crt->raw.len;
4176         if( n > MBEDTLS_SSL_MAX_CONTENT_LEN - 3 - i )
4177         {
4178             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
4179                            i + 3 + n, MBEDTLS_SSL_MAX_CONTENT_LEN ) );
4180             return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
4181         }
4182 
4183         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
4184         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
4185         ssl->out_msg[i + 2] = (unsigned char)( n       );
4186 
4187         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
4188         i += n; crt = crt->next;
4189     }
4190 
4191     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
4192     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
4193     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
4194 
4195     ssl->out_msglen  = i;
4196     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4197     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
4198 
4199 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
4200 write_msg:
4201 #endif
4202 
4203     ssl->state++;
4204 
4205     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4206     {
4207         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4208         return( ret );
4209     }
4210 
4211     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
4212 
4213     return( ret );
4214 }
4215 
mbedtls_ssl_parse_certificate(mbedtls_ssl_context * ssl)4216 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4217 {
4218     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4219     size_t i, n;
4220     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4221     int authmode = ssl->conf->authmode;
4222 
4223     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4224 
4225     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4226         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4227         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4228         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4229     {
4230         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4231         ssl->state++;
4232         return( 0 );
4233     }
4234 
4235 #if defined(MBEDTLS_SSL_SRV_C)
4236     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4237         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
4238     {
4239         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4240         ssl->state++;
4241         return( 0 );
4242     }
4243 
4244 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4245     if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
4246         authmode = ssl->handshake->sni_authmode;
4247 #endif
4248 
4249     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4250         authmode == MBEDTLS_SSL_VERIFY_NONE )
4251     {
4252         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
4253         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4254         ssl->state++;
4255         return( 0 );
4256     }
4257 #endif
4258 
4259     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4260     {
4261         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4262         return( ret );
4263     }
4264 
4265     ssl->state++;
4266 
4267 #if defined(MBEDTLS_SSL_SRV_C)
4268 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4269     /*
4270      * Check if the client sent an empty certificate
4271      */
4272     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
4273         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4274     {
4275         if( ssl->in_msglen  == 2                        &&
4276             ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
4277             ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
4278             ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4279         {
4280             MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
4281 
4282             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4283             if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4284                 return( 0 );
4285             else
4286                 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4287         }
4288     }
4289 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4290 
4291 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
4292     defined(MBEDTLS_SSL_PROTO_TLS1_2)
4293     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
4294         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
4295     {
4296         if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
4297             ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
4298             ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
4299             memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
4300         {
4301             MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
4302 
4303             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4304             if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4305                 return( 0 );
4306             else
4307                 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4308         }
4309     }
4310 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
4311           MBEDTLS_SSL_PROTO_TLS1_2 */
4312 #endif /* MBEDTLS_SSL_SRV_C */
4313 
4314     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
4315     {
4316         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4317         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4318     }
4319 
4320     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
4321         ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
4322     {
4323         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4324         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4325     }
4326 
4327     i = mbedtls_ssl_hs_hdr_len( ssl );
4328 
4329     /*
4330      * Same message structure as in mbedtls_ssl_write_certificate()
4331      */
4332     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
4333 
4334     if( ssl->in_msg[i] != 0 ||
4335         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
4336     {
4337         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4338         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4339     }
4340 
4341     /* In case we tried to reuse a session but it failed */
4342     if( ssl->session_negotiate->peer_cert != NULL )
4343     {
4344         mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
4345         mbedtls_free( ssl->session_negotiate->peer_cert );
4346     }
4347 
4348     if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
4349                     sizeof( mbedtls_x509_crt ) ) ) == NULL )
4350     {
4351         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
4352                        sizeof( mbedtls_x509_crt ) ) );
4353         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4354     }
4355 
4356     mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
4357 
4358     i += 3;
4359 
4360     while( i < ssl->in_hslen )
4361     {
4362         if( ssl->in_msg[i] != 0 )
4363         {
4364             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4365             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4366         }
4367 
4368         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
4369             | (unsigned int) ssl->in_msg[i + 2];
4370         i += 3;
4371 
4372         if( n < 128 || i + n > ssl->in_hslen )
4373         {
4374             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4375             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4376         }
4377 
4378         ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
4379                                   ssl->in_msg + i, n );
4380         if( 0 != ret && ( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND ) != ret )
4381         {
4382             MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
4383             return( ret );
4384         }
4385 
4386         i += n;
4387     }
4388 
4389     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
4390 
4391     /*
4392      * On client, make sure the server cert doesn't change during renego to
4393      * avoid "triple handshake" attack: https://secure-resumption.com/
4394      */
4395 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
4396     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
4397         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
4398     {
4399         if( ssl->session->peer_cert == NULL )
4400         {
4401             MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
4402             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4403         }
4404 
4405         if( ssl->session->peer_cert->raw.len !=
4406             ssl->session_negotiate->peer_cert->raw.len ||
4407             memcmp( ssl->session->peer_cert->raw.p,
4408                     ssl->session_negotiate->peer_cert->raw.p,
4409                     ssl->session->peer_cert->raw.len ) != 0 )
4410         {
4411             MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
4412             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4413         }
4414     }
4415 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
4416 
4417     if( authmode != MBEDTLS_SSL_VERIFY_NONE )
4418     {
4419         mbedtls_x509_crt *ca_chain;
4420         mbedtls_x509_crl *ca_crl;
4421 
4422 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4423         if( ssl->handshake->sni_ca_chain != NULL )
4424         {
4425             ca_chain = ssl->handshake->sni_ca_chain;
4426             ca_crl   = ssl->handshake->sni_ca_crl;
4427         }
4428         else
4429 #endif
4430         {
4431             ca_chain = ssl->conf->ca_chain;
4432             ca_crl   = ssl->conf->ca_crl;
4433         }
4434 
4435         if( ca_chain == NULL )
4436         {
4437             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
4438             return( MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED );
4439         }
4440 
4441         /*
4442          * Main check: verify certificate
4443          */
4444         ret = mbedtls_x509_crt_verify_with_profile(
4445                                 ssl->session_negotiate->peer_cert,
4446                                 ca_chain, ca_crl,
4447                                 ssl->conf->cert_profile,
4448                                 ssl->hostname,
4449                                &ssl->session_negotiate->verify_result,
4450                                 ssl->conf->f_vrfy, ssl->conf->p_vrfy );
4451 
4452         if( ret != 0 )
4453         {
4454             MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
4455         }
4456 
4457         /*
4458          * Secondary checks: always done, but change 'ret' only if it was 0
4459          */
4460 
4461 #if defined(MBEDTLS_ECP_C)
4462         {
4463             const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
4464 
4465             /* If certificate uses an EC key, make sure the curve is OK */
4466             if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
4467                 mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
4468             {
4469                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
4470                 if( ret == 0 )
4471                     ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4472             }
4473         }
4474 #endif /* MBEDTLS_ECP_C */
4475 
4476         if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
4477                                   ciphersuite_info,
4478                                   ! ssl->conf->endpoint,
4479                                  &ssl->session_negotiate->verify_result ) != 0 )
4480         {
4481             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
4482             if( ret == 0 )
4483                 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4484         }
4485 
4486         if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4487             ret = 0;
4488     }
4489 
4490     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
4491 
4492     return( ret );
4493 }
4494 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
4495           !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
4496           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
4497           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
4498           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
4499           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
4500           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
4501 
mbedtls_ssl_write_change_cipher_spec(mbedtls_ssl_context * ssl)4502 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
4503 {
4504     int ret;
4505 
4506     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
4507 
4508     ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4509     ssl->out_msglen  = 1;
4510     ssl->out_msg[0]  = 1;
4511 
4512     ssl->state++;
4513 
4514     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4515     {
4516         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4517         return( ret );
4518     }
4519 
4520     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
4521 
4522     return( 0 );
4523 }
4524 
mbedtls_ssl_parse_change_cipher_spec(mbedtls_ssl_context * ssl)4525 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
4526 {
4527     int ret;
4528 
4529     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
4530 
4531     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4532     {
4533         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4534         return( ret );
4535     }
4536 
4537     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
4538     {
4539         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4540         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4541     }
4542 
4543     if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )
4544     {
4545         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4546         return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );
4547     }
4548 
4549     /*
4550      * Switch to our negotiated transform and session parameters for inbound
4551      * data.
4552      */
4553     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
4554     ssl->transform_in = ssl->transform_negotiate;
4555     ssl->session_in = ssl->session_negotiate;
4556 
4557 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4558     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4559     {
4560 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4561         ssl_dtls_replay_reset( ssl );
4562 #endif
4563 
4564         /* Increment epoch */
4565         if( ++ssl->in_epoch == 0 )
4566         {
4567             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
4568             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
4569         }
4570     }
4571     else
4572 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4573     memset( ssl->in_ctr, 0, 8 );
4574 
4575     /*
4576      * Set the in_msg pointer to the correct location based on IV length
4577      */
4578     if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
4579     {
4580         ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen -
4581                       ssl->transform_negotiate->fixed_ivlen;
4582     }
4583     else
4584         ssl->in_msg = ssl->in_iv;
4585 
4586 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
4587     if( mbedtls_ssl_hw_record_activate != NULL )
4588     {
4589         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
4590         {
4591             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
4592             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
4593         }
4594     }
4595 #endif
4596 
4597     ssl->state++;
4598 
4599     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
4600 
4601     return( 0 );
4602 }
4603 
mbedtls_ssl_optimize_checksum(mbedtls_ssl_context * ssl,const mbedtls_ssl_ciphersuite_t * ciphersuite_info)4604 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
4605                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
4606 {
4607     ((void) ciphersuite_info);
4608 
4609 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4610     defined(MBEDTLS_SSL_PROTO_TLS1_1)
4611     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
4612         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
4613     else
4614 #endif
4615 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4616 #if defined(MBEDTLS_SHA512_C)
4617     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
4618         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
4619     else
4620 #endif
4621 #if defined(MBEDTLS_SHA256_C)
4622     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
4623         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
4624     else
4625 #endif
4626 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4627     {
4628         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4629         return;
4630     }
4631 }
4632 
mbedtls_ssl_reset_checksum(mbedtls_ssl_context * ssl)4633 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
4634 {
4635 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4636     defined(MBEDTLS_SSL_PROTO_TLS1_1)
4637      mbedtls_md5_starts( &ssl->handshake->fin_md5  );
4638     mbedtls_sha1_starts( &ssl->handshake->fin_sha1 );
4639 #endif
4640 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4641 #if defined(MBEDTLS_SHA256_C)
4642     mbedtls_sha256_starts( &ssl->handshake->fin_sha256, 0 );
4643 #endif
4644 #if defined(MBEDTLS_SHA512_C)
4645     mbedtls_sha512_starts( &ssl->handshake->fin_sha512, 1 );
4646 #endif
4647 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4648 }
4649 
ssl_update_checksum_start(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)4650 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
4651                                        const unsigned char *buf, size_t len )
4652 {
4653 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4654     defined(MBEDTLS_SSL_PROTO_TLS1_1)
4655      mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len );
4656     mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len );
4657 #endif
4658 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4659 #if defined(MBEDTLS_SHA256_C)
4660     mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
4661 #endif
4662 #if defined(MBEDTLS_SHA512_C)
4663     mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len );
4664 #endif
4665 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4666 }
4667 
4668 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4669     defined(MBEDTLS_SSL_PROTO_TLS1_1)
ssl_update_checksum_md5sha1(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)4670 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
4671                                          const unsigned char *buf, size_t len )
4672 {
4673      mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len );
4674     mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len );
4675 }
4676 #endif
4677 
4678 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4679 #if defined(MBEDTLS_SHA256_C)
ssl_update_checksum_sha256(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)4680 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
4681                                         const unsigned char *buf, size_t len )
4682 {
4683     mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len );
4684 }
4685 #endif
4686 
4687 #if defined(MBEDTLS_SHA512_C)
ssl_update_checksum_sha384(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)4688 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
4689                                         const unsigned char *buf, size_t len )
4690 {
4691     mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len );
4692 }
4693 #endif
4694 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4695 
4696 #if defined(MBEDTLS_SSL_PROTO_SSL3)
ssl_calc_finished_ssl(mbedtls_ssl_context * ssl,unsigned char * buf,int from)4697 static void ssl_calc_finished_ssl(
4698                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4699 {
4700     const char *sender;
4701     mbedtls_md5_context  md5;
4702     mbedtls_sha1_context sha1;
4703 
4704     unsigned char padbuf[48];
4705     unsigned char md5sum[16];
4706     unsigned char sha1sum[20];
4707 
4708     mbedtls_ssl_session *session = ssl->session_negotiate;
4709     if( !session )
4710         session = ssl->session;
4711 
4712     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
4713 
4714     mbedtls_md5_init( &md5 );
4715     mbedtls_sha1_init( &sha1 );
4716 
4717     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
4718     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
4719 
4720     /*
4721      * SSLv3:
4722      *   hash =
4723      *      MD5( master + pad2 +
4724      *          MD5( handshake + sender + master + pad1 ) )
4725      *   + SHA1( master + pad2 +
4726      *         SHA1( handshake + sender + master + pad1 ) )
4727      */
4728 
4729 #if !defined(MBEDTLS_MD5_ALT)
4730     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
4731                     md5.state, sizeof(  md5.state ) );
4732 #endif
4733 
4734 #if !defined(MBEDTLS_SHA1_ALT)
4735     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
4736                    sha1.state, sizeof( sha1.state ) );
4737 #endif
4738 
4739     sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
4740                                        : "SRVR";
4741 
4742     memset( padbuf, 0x36, 48 );
4743 
4744     mbedtls_md5_update( &md5, (const unsigned char *) sender, 4 );
4745     mbedtls_md5_update( &md5, session->master, 48 );
4746     mbedtls_md5_update( &md5, padbuf, 48 );
4747     mbedtls_md5_finish( &md5, md5sum );
4748 
4749     mbedtls_sha1_update( &sha1, (const unsigned char *) sender, 4 );
4750     mbedtls_sha1_update( &sha1, session->master, 48 );
4751     mbedtls_sha1_update( &sha1, padbuf, 40 );
4752     mbedtls_sha1_finish( &sha1, sha1sum );
4753 
4754     memset( padbuf, 0x5C, 48 );
4755 
4756     mbedtls_md5_starts( &md5 );
4757     mbedtls_md5_update( &md5, session->master, 48 );
4758     mbedtls_md5_update( &md5, padbuf, 48 );
4759     mbedtls_md5_update( &md5, md5sum, 16 );
4760     mbedtls_md5_finish( &md5, buf );
4761 
4762     mbedtls_sha1_starts( &sha1 );
4763     mbedtls_sha1_update( &sha1, session->master, 48 );
4764     mbedtls_sha1_update( &sha1, padbuf , 40 );
4765     mbedtls_sha1_update( &sha1, sha1sum, 20 );
4766     mbedtls_sha1_finish( &sha1, buf + 16 );
4767 
4768     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
4769 
4770     mbedtls_md5_free(  &md5  );
4771     mbedtls_sha1_free( &sha1 );
4772 
4773     mbedtls_zeroize(  padbuf, sizeof(  padbuf ) );
4774     mbedtls_zeroize(  md5sum, sizeof(  md5sum ) );
4775     mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
4776 
4777     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
4778 }
4779 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4780 
4781 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
ssl_calc_finished_tls(mbedtls_ssl_context * ssl,unsigned char * buf,int from)4782 static void ssl_calc_finished_tls(
4783                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4784 {
4785     int len = 12;
4786     const char *sender;
4787     mbedtls_md5_context  md5;
4788     mbedtls_sha1_context sha1;
4789     unsigned char padbuf[36];
4790 
4791     mbedtls_ssl_session *session = ssl->session_negotiate;
4792     if( !session )
4793         session = ssl->session;
4794 
4795     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
4796 
4797     mbedtls_md5_init( &md5 );
4798     mbedtls_sha1_init( &sha1 );
4799 
4800     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
4801     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
4802 
4803     /*
4804      * TLSv1:
4805      *   hash = PRF( master, finished_label,
4806      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
4807      */
4808 
4809 #if !defined(MBEDTLS_MD5_ALT)
4810     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
4811                     md5.state, sizeof(  md5.state ) );
4812 #endif
4813 
4814 #if !defined(MBEDTLS_SHA1_ALT)
4815     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
4816                    sha1.state, sizeof( sha1.state ) );
4817 #endif
4818 
4819     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
4820              ? "client finished"
4821              : "server finished";
4822 
4823     mbedtls_md5_finish(  &md5, padbuf );
4824     mbedtls_sha1_finish( &sha1, padbuf + 16 );
4825 
4826     ssl->handshake->tls_prf( session->master, 48, sender,
4827                              padbuf, 36, buf, len );
4828 
4829     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
4830 
4831     mbedtls_md5_free(  &md5  );
4832     mbedtls_sha1_free( &sha1 );
4833 
4834     mbedtls_zeroize(  padbuf, sizeof(  padbuf ) );
4835 
4836     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
4837 }
4838 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
4839 
4840 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4841 #if defined(MBEDTLS_SHA256_C)
ssl_calc_finished_tls_sha256(mbedtls_ssl_context * ssl,unsigned char * buf,int from)4842 static void ssl_calc_finished_tls_sha256(
4843                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4844 {
4845     int len = 12;
4846     const char *sender;
4847     mbedtls_sha256_context sha256;
4848     unsigned char padbuf[32];
4849 
4850     mbedtls_ssl_session *session = ssl->session_negotiate;
4851     if( !session )
4852         session = ssl->session;
4853 
4854     mbedtls_sha256_init( &sha256 );
4855 
4856     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
4857 
4858     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
4859 
4860     /*
4861      * TLSv1.2:
4862      *   hash = PRF( master, finished_label,
4863      *               Hash( handshake ) )[0.11]
4864      */
4865 
4866 #if !defined(MBEDTLS_SHA256_ALT)
4867     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
4868                    sha256.state, sizeof( sha256.state ) );
4869 #endif
4870 
4871     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
4872              ? "client finished"
4873              : "server finished";
4874 
4875     mbedtls_sha256_finish( &sha256, padbuf );
4876 
4877     ssl->handshake->tls_prf( session->master, 48, sender,
4878                              padbuf, 32, buf, len );
4879 
4880     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
4881 
4882     mbedtls_sha256_free( &sha256 );
4883 
4884     mbedtls_zeroize(  padbuf, sizeof(  padbuf ) );
4885 
4886     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
4887 }
4888 #endif /* MBEDTLS_SHA256_C */
4889 
4890 #if defined(MBEDTLS_SHA512_C)
ssl_calc_finished_tls_sha384(mbedtls_ssl_context * ssl,unsigned char * buf,int from)4891 static void ssl_calc_finished_tls_sha384(
4892                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
4893 {
4894     int len = 12;
4895     const char *sender;
4896     mbedtls_sha512_context sha512;
4897     unsigned char padbuf[48];
4898 
4899     mbedtls_ssl_session *session = ssl->session_negotiate;
4900     if( !session )
4901         session = ssl->session;
4902 
4903     mbedtls_sha512_init( &sha512 );
4904 
4905     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
4906 
4907     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
4908 
4909     /*
4910      * TLSv1.2:
4911      *   hash = PRF( master, finished_label,
4912      *               Hash( handshake ) )[0.11]
4913      */
4914 
4915 #if !defined(MBEDTLS_SHA512_ALT)
4916     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
4917                    sha512.state, sizeof( sha512.state ) );
4918 #endif
4919 
4920     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
4921              ? "client finished"
4922              : "server finished";
4923 
4924     mbedtls_sha512_finish( &sha512, padbuf );
4925 
4926     ssl->handshake->tls_prf( session->master, 48, sender,
4927                              padbuf, 48, buf, len );
4928 
4929     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
4930 
4931     mbedtls_sha512_free( &sha512 );
4932 
4933     mbedtls_zeroize(  padbuf, sizeof( padbuf ) );
4934 
4935     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
4936 }
4937 #endif /* MBEDTLS_SHA512_C */
4938 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4939 
ssl_handshake_wrapup_free_hs_transform(mbedtls_ssl_context * ssl)4940 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
4941 {
4942     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
4943 
4944     /*
4945      * Free our handshake params
4946      */
4947     mbedtls_ssl_handshake_free( ssl->handshake );
4948     mbedtls_free( ssl->handshake );
4949     ssl->handshake = NULL;
4950 
4951     /*
4952      * Free the previous transform and swith in the current one
4953      */
4954     if( ssl->transform )
4955     {
4956         mbedtls_ssl_transform_free( ssl->transform );
4957         mbedtls_free( ssl->transform );
4958     }
4959     ssl->transform = ssl->transform_negotiate;
4960     ssl->transform_negotiate = NULL;
4961 
4962     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
4963 }
4964 
mbedtls_ssl_handshake_wrapup(mbedtls_ssl_context * ssl)4965 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
4966 {
4967     int resume = ssl->handshake->resume;
4968 
4969     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
4970 
4971 #if defined(MBEDTLS_SSL_RENEGOTIATION)
4972     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
4973     {
4974         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
4975         ssl->renego_records_seen = 0;
4976     }
4977 #endif
4978 
4979     /*
4980      * Free the previous session and switch in the current one
4981      */
4982     if( ssl->session )
4983     {
4984 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
4985         /* RFC 7366 3.1: keep the EtM state */
4986         ssl->session_negotiate->encrypt_then_mac =
4987                   ssl->session->encrypt_then_mac;
4988 #endif
4989 
4990         mbedtls_ssl_session_free( ssl->session );
4991         mbedtls_free( ssl->session );
4992     }
4993     ssl->session = ssl->session_negotiate;
4994     ssl->session_negotiate = NULL;
4995 
4996     /*
4997      * Add cache entry
4998      */
4999     if( ssl->conf->f_set_cache != NULL &&
5000         ssl->session->id_len != 0 &&
5001         resume == 0 )
5002     {
5003         if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
5004             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
5005     }
5006 
5007 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5008     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5009         ssl->handshake->flight != NULL )
5010     {
5011         /* Cancel handshake timer */
5012         ssl_set_timer( ssl, 0 );
5013 
5014         /* Keep last flight around in case we need to resend it:
5015          * we need the handshake and transform structures for that */
5016         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
5017     }
5018     else
5019 #endif
5020         ssl_handshake_wrapup_free_hs_transform( ssl );
5021 
5022     ssl->state++;
5023 
5024     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
5025 }
5026 
mbedtls_ssl_write_finished(mbedtls_ssl_context * ssl)5027 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
5028 {
5029     int ret, hash_len;
5030 
5031     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
5032 
5033     /*
5034      * Set the out_msg pointer to the correct location based on IV length
5035      */
5036     if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
5037     {
5038         ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen -
5039                        ssl->transform_negotiate->fixed_ivlen;
5040     }
5041     else
5042         ssl->out_msg = ssl->out_iv;
5043 
5044     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
5045 
5046     /*
5047      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
5048      * may define some other value. Currently (early 2016), no defined
5049      * ciphersuite does this (and this is unlikely to change as activity has
5050      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
5051      */
5052     hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
5053 
5054 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5055     ssl->verify_data_len = hash_len;
5056     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
5057 #endif
5058 
5059     ssl->out_msglen  = 4 + hash_len;
5060     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
5061     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
5062 
5063     /*
5064      * In case of session resuming, invert the client and server
5065      * ChangeCipherSpec messages order.
5066      */
5067     if( ssl->handshake->resume != 0 )
5068     {
5069 #if defined(MBEDTLS_SSL_CLI_C)
5070         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5071             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5072 #endif
5073 #if defined(MBEDTLS_SSL_SRV_C)
5074         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5075             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5076 #endif
5077     }
5078     else
5079         ssl->state++;
5080 
5081     /*
5082      * Switch to our negotiated transform and session parameters for outbound
5083      * data.
5084      */
5085     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
5086 
5087 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5088     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5089     {
5090         unsigned char i;
5091 
5092         /* Remember current epoch settings for resending */
5093         ssl->handshake->alt_transform_out = ssl->transform_out;
5094         memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 );
5095 
5096         /* Set sequence_number to zero */
5097         memset( ssl->out_ctr + 2, 0, 6 );
5098 
5099         /* Increment epoch */
5100         for( i = 2; i > 0; i-- )
5101             if( ++ssl->out_ctr[i - 1] != 0 )
5102                 break;
5103 
5104         /* The loop goes to its end iff the counter is wrapping */
5105         if( i == 0 )
5106         {
5107             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
5108             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
5109         }
5110     }
5111     else
5112 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5113     memset( ssl->out_ctr, 0, 8 );
5114 
5115     ssl->transform_out = ssl->transform_negotiate;
5116     ssl->session_out = ssl->session_negotiate;
5117 
5118 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5119     if( mbedtls_ssl_hw_record_activate != NULL )
5120     {
5121         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
5122         {
5123             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
5124             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5125         }
5126     }
5127 #endif
5128 
5129 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5130     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5131         mbedtls_ssl_send_flight_completed( ssl );
5132 #endif
5133 
5134     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
5135     {
5136         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
5137         return( ret );
5138     }
5139 
5140     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
5141 
5142     return( 0 );
5143 }
5144 
5145 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5146 #define SSL_MAX_HASH_LEN 36
5147 #else
5148 #define SSL_MAX_HASH_LEN 12
5149 #endif
5150 
mbedtls_ssl_parse_finished(mbedtls_ssl_context * ssl)5151 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
5152 {
5153     int ret;
5154     unsigned int hash_len;
5155     unsigned char buf[SSL_MAX_HASH_LEN];
5156 
5157     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
5158 
5159     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
5160 
5161     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
5162     {
5163         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5164         return( ret );
5165     }
5166 
5167     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
5168     {
5169         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5170         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5171     }
5172 
5173     /* There is currently no ciphersuite using another length with TLS 1.2 */
5174 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5175     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
5176         hash_len = 36;
5177     else
5178 #endif
5179         hash_len = 12;
5180 
5181     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
5182         ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
5183     {
5184         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5185         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5186     }
5187 
5188     if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
5189                       buf, hash_len ) != 0 )
5190     {
5191         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5192         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5193     }
5194 
5195 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5196     ssl->verify_data_len = hash_len;
5197     memcpy( ssl->peer_verify_data, buf, hash_len );
5198 #endif
5199 
5200     if( ssl->handshake->resume != 0 )
5201     {
5202 #if defined(MBEDTLS_SSL_CLI_C)
5203         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5204             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5205 #endif
5206 #if defined(MBEDTLS_SSL_SRV_C)
5207         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5208             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5209 #endif
5210     }
5211     else
5212         ssl->state++;
5213 
5214 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5215     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5216         mbedtls_ssl_recv_flight_completed( ssl );
5217 #endif
5218 
5219     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
5220 
5221     return( 0 );
5222 }
5223 
ssl_handshake_params_init(mbedtls_ssl_handshake_params * handshake)5224 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
5225 {
5226     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
5227 
5228 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5229     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5230      mbedtls_md5_init(   &handshake->fin_md5  );
5231     mbedtls_sha1_init(   &handshake->fin_sha1 );
5232      mbedtls_md5_starts( &handshake->fin_md5  );
5233     mbedtls_sha1_starts( &handshake->fin_sha1 );
5234 #endif
5235 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5236 #if defined(MBEDTLS_SHA256_C)
5237     mbedtls_sha256_init(   &handshake->fin_sha256    );
5238     mbedtls_sha256_starts( &handshake->fin_sha256, 0 );
5239 #endif
5240 #if defined(MBEDTLS_SHA512_C)
5241     mbedtls_sha512_init(   &handshake->fin_sha512    );
5242     mbedtls_sha512_starts( &handshake->fin_sha512, 1 );
5243 #endif
5244 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5245 
5246     handshake->update_checksum = ssl_update_checksum_start;
5247     handshake->sig_alg = MBEDTLS_SSL_HASH_SHA1;
5248 
5249 #if defined(MBEDTLS_DHM_C)
5250     mbedtls_dhm_init( &handshake->dhm_ctx );
5251 #endif
5252 #if defined(MBEDTLS_ECDH_C)
5253     mbedtls_ecdh_init( &handshake->ecdh_ctx );
5254 #endif
5255 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5256     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
5257 #if defined(MBEDTLS_SSL_CLI_C)
5258     handshake->ecjpake_cache = NULL;
5259     handshake->ecjpake_cache_len = 0;
5260 #endif
5261 #endif
5262 
5263 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5264     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
5265 #endif
5266 }
5267 
ssl_transform_init(mbedtls_ssl_transform * transform)5268 static void ssl_transform_init( mbedtls_ssl_transform *transform )
5269 {
5270     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
5271 
5272     mbedtls_cipher_init( &transform->cipher_ctx_enc );
5273     mbedtls_cipher_init( &transform->cipher_ctx_dec );
5274 
5275     mbedtls_md_init( &transform->md_ctx_enc );
5276     mbedtls_md_init( &transform->md_ctx_dec );
5277 }
5278 
mbedtls_ssl_session_init(mbedtls_ssl_session * session)5279 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
5280 {
5281     memset( session, 0, sizeof(mbedtls_ssl_session) );
5282 }
5283 
ssl_handshake_init(mbedtls_ssl_context * ssl)5284 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
5285 {
5286     /* Clear old handshake information if present */
5287     if( ssl->transform_negotiate )
5288         mbedtls_ssl_transform_free( ssl->transform_negotiate );
5289     if( ssl->session_negotiate )
5290         mbedtls_ssl_session_free( ssl->session_negotiate );
5291     if( ssl->handshake )
5292         mbedtls_ssl_handshake_free( ssl->handshake );
5293 
5294     /*
5295      * Either the pointers are now NULL or cleared properly and can be freed.
5296      * Now allocate missing structures.
5297      */
5298     if( ssl->transform_negotiate == NULL )
5299     {
5300         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
5301     }
5302 
5303     if( ssl->session_negotiate == NULL )
5304     {
5305         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
5306     }
5307 
5308     if( ssl->handshake == NULL )
5309     {
5310         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
5311     }
5312 
5313     /* All pointers should exist and can be directly freed without issue */
5314     if( ssl->handshake == NULL ||
5315         ssl->transform_negotiate == NULL ||
5316         ssl->session_negotiate == NULL )
5317     {
5318         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
5319 
5320         mbedtls_free( ssl->handshake );
5321         mbedtls_free( ssl->transform_negotiate );
5322         mbedtls_free( ssl->session_negotiate );
5323 
5324         ssl->handshake = NULL;
5325         ssl->transform_negotiate = NULL;
5326         ssl->session_negotiate = NULL;
5327 
5328         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5329     }
5330 
5331     /* Initialize structures */
5332     mbedtls_ssl_session_init( ssl->session_negotiate );
5333     ssl_transform_init( ssl->transform_negotiate );
5334     ssl_handshake_params_init( ssl->handshake );
5335 
5336 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5337     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5338     {
5339         ssl->handshake->alt_transform_out = ssl->transform_out;
5340 
5341         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5342             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
5343         else
5344             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
5345 
5346         ssl_set_timer( ssl, 0 );
5347     }
5348 #endif
5349 
5350     return( 0 );
5351 }
5352 
5353 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5354 /* Dummy cookie callbacks for defaults */
ssl_cookie_write_dummy(void * ctx,unsigned char ** p,unsigned char * end,const unsigned char * cli_id,size_t cli_id_len)5355 static int ssl_cookie_write_dummy( void *ctx,
5356                       unsigned char **p, unsigned char *end,
5357                       const unsigned char *cli_id, size_t cli_id_len )
5358 {
5359     ((void) ctx);
5360     ((void) p);
5361     ((void) end);
5362     ((void) cli_id);
5363     ((void) cli_id_len);
5364 
5365     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5366 }
5367 
ssl_cookie_check_dummy(void * ctx,const unsigned char * cookie,size_t cookie_len,const unsigned char * cli_id,size_t cli_id_len)5368 static int ssl_cookie_check_dummy( void *ctx,
5369                       const unsigned char *cookie, size_t cookie_len,
5370                       const unsigned char *cli_id, size_t cli_id_len )
5371 {
5372     ((void) ctx);
5373     ((void) cookie);
5374     ((void) cookie_len);
5375     ((void) cli_id);
5376     ((void) cli_id_len);
5377 
5378     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5379 }
5380 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
5381 
5382 /*
5383  * Initialize an SSL context
5384  */
mbedtls_ssl_init(mbedtls_ssl_context * ssl)5385 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
5386 {
5387     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
5388 }
5389 
5390 /*
5391  * Setup an SSL context
5392  */
mbedtls_ssl_setup(mbedtls_ssl_context * ssl,const mbedtls_ssl_config * conf)5393 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
5394                        const mbedtls_ssl_config *conf )
5395 {
5396     int ret;
5397     const size_t len = MBEDTLS_SSL_BUFFER_LEN;
5398 
5399     ssl->conf = conf;
5400 
5401     /*
5402      * Prepare base structures
5403      */
5404     if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL ||
5405         ( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL )
5406     {
5407         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) );
5408         mbedtls_free( ssl->in_buf );
5409         ssl->in_buf = NULL;
5410         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5411     }
5412 
5413 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5414     if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5415     {
5416         ssl->out_hdr = ssl->out_buf;
5417         ssl->out_ctr = ssl->out_buf +  3;
5418         ssl->out_len = ssl->out_buf + 11;
5419         ssl->out_iv  = ssl->out_buf + 13;
5420         ssl->out_msg = ssl->out_buf + 13;
5421 
5422         ssl->in_hdr = ssl->in_buf;
5423         ssl->in_ctr = ssl->in_buf +  3;
5424         ssl->in_len = ssl->in_buf + 11;
5425         ssl->in_iv  = ssl->in_buf + 13;
5426         ssl->in_msg = ssl->in_buf + 13;
5427     }
5428     else
5429 #endif
5430     {
5431         ssl->out_ctr = ssl->out_buf;
5432         ssl->out_hdr = ssl->out_buf +  8;
5433         ssl->out_len = ssl->out_buf + 11;
5434         ssl->out_iv  = ssl->out_buf + 13;
5435         ssl->out_msg = ssl->out_buf + 13;
5436 
5437         ssl->in_ctr = ssl->in_buf;
5438         ssl->in_hdr = ssl->in_buf +  8;
5439         ssl->in_len = ssl->in_buf + 11;
5440         ssl->in_iv  = ssl->in_buf + 13;
5441         ssl->in_msg = ssl->in_buf + 13;
5442     }
5443 
5444     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5445         return( ret );
5446 
5447     return( 0 );
5448 }
5449 
5450 /*
5451  * Reset an initialized and used SSL context for re-use while retaining
5452  * all application-set variables, function pointers and data.
5453  *
5454  * If partial is non-zero, keep data in the input buffer and client ID.
5455  * (Use when a DTLS client reconnects from the same port.)
5456  */
ssl_session_reset_int(mbedtls_ssl_context * ssl,int partial)5457 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
5458 {
5459     int ret;
5460 
5461     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
5462 
5463     /* Cancel any possibly running timer */
5464     ssl_set_timer( ssl, 0 );
5465 
5466 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5467     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
5468     ssl->renego_records_seen = 0;
5469 
5470     ssl->verify_data_len = 0;
5471     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5472     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5473 #endif
5474     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
5475 
5476     ssl->in_offt = NULL;
5477 
5478     ssl->in_msg = ssl->in_buf + 13;
5479     ssl->in_msgtype = 0;
5480     ssl->in_msglen = 0;
5481     if( partial == 0 )
5482         ssl->in_left = 0;
5483 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5484     ssl->next_record_offset = 0;
5485     ssl->in_epoch = 0;
5486 #endif
5487 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5488     ssl_dtls_replay_reset( ssl );
5489 #endif
5490 
5491     ssl->in_hslen = 0;
5492     ssl->nb_zero = 0;
5493     ssl->record_read = 0;
5494 
5495     ssl->out_msg = ssl->out_buf + 13;
5496     ssl->out_msgtype = 0;
5497     ssl->out_msglen = 0;
5498     ssl->out_left = 0;
5499 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
5500     if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
5501         ssl->split_done = 0;
5502 #endif
5503 
5504     ssl->transform_in = NULL;
5505     ssl->transform_out = NULL;
5506 
5507     memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5508     if( partial == 0 )
5509         memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5510 
5511 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5512     if( mbedtls_ssl_hw_record_reset != NULL )
5513     {
5514         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
5515         if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
5516         {
5517             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
5518             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5519         }
5520     }
5521 #endif
5522 
5523     if( ssl->transform )
5524     {
5525         mbedtls_ssl_transform_free( ssl->transform );
5526         mbedtls_free( ssl->transform );
5527         ssl->transform = NULL;
5528     }
5529 
5530     if( ssl->session )
5531     {
5532         mbedtls_ssl_session_free( ssl->session );
5533         mbedtls_free( ssl->session );
5534         ssl->session = NULL;
5535     }
5536 
5537 #if defined(MBEDTLS_SSL_ALPN)
5538     ssl->alpn_chosen = NULL;
5539 #endif
5540 
5541 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5542     if( partial == 0 )
5543     {
5544         mbedtls_free( ssl->cli_id );
5545         ssl->cli_id = NULL;
5546         ssl->cli_id_len = 0;
5547     }
5548 #endif
5549 
5550     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5551         return( ret );
5552 
5553     return( 0 );
5554 }
5555 
5556 /*
5557  * Reset an initialized and used SSL context for re-use while retaining
5558  * all application-set variables, function pointers and data.
5559  */
mbedtls_ssl_session_reset(mbedtls_ssl_context * ssl)5560 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
5561 {
5562     return( ssl_session_reset_int( ssl, 0 ) );
5563 }
5564 
5565 /*
5566  * SSL set accessors
5567  */
mbedtls_ssl_conf_endpoint(mbedtls_ssl_config * conf,int endpoint)5568 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
5569 {
5570     conf->endpoint   = endpoint;
5571 }
5572 
mbedtls_ssl_conf_transport(mbedtls_ssl_config * conf,int transport)5573 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
5574 {
5575     conf->transport = transport;
5576 }
5577 
5578 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
mbedtls_ssl_conf_dtls_anti_replay(mbedtls_ssl_config * conf,char mode)5579 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
5580 {
5581     conf->anti_replay = mode;
5582 }
5583 #endif
5584 
5585 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
mbedtls_ssl_conf_dtls_badmac_limit(mbedtls_ssl_config * conf,unsigned limit)5586 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
5587 {
5588     conf->badmac_limit = limit;
5589 }
5590 #endif
5591 
5592 #if defined(MBEDTLS_SSL_PROTO_DTLS)
mbedtls_ssl_conf_handshake_timeout(mbedtls_ssl_config * conf,uint32_t min,uint32_t max)5593 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max )
5594 {
5595     conf->hs_timeout_min = min;
5596     conf->hs_timeout_max = max;
5597 }
5598 #endif
5599 
mbedtls_ssl_conf_authmode(mbedtls_ssl_config * conf,int authmode)5600 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
5601 {
5602     conf->authmode   = authmode;
5603 }
5604 
5605 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_verify(mbedtls_ssl_config * conf,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)5606 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
5607                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
5608                      void *p_vrfy )
5609 {
5610     conf->f_vrfy      = f_vrfy;
5611     conf->p_vrfy      = p_vrfy;
5612 }
5613 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5614 
mbedtls_ssl_conf_rng(mbedtls_ssl_config * conf,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)5615 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
5616                   int (*f_rng)(void *, unsigned char *, size_t),
5617                   void *p_rng )
5618 {
5619     conf->f_rng      = f_rng;
5620     conf->p_rng      = p_rng;
5621 }
5622 
mbedtls_ssl_conf_dbg(mbedtls_ssl_config * conf,void (* f_dbg)(void *,int,const char *,int,const char *),void * p_dbg)5623 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
5624                   void (*f_dbg)(void *, int, const char *, int, const char *),
5625                   void  *p_dbg )
5626 {
5627     conf->f_dbg      = f_dbg;
5628     conf->p_dbg      = p_dbg;
5629 }
5630 
mbedtls_ssl_set_bio(mbedtls_ssl_context * ssl,void * p_bio,mbedtls_ssl_send_t * f_send,mbedtls_ssl_recv_t * f_recv,mbedtls_ssl_recv_timeout_t * f_recv_timeout)5631 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
5632         void *p_bio,
5633         mbedtls_ssl_send_t *f_send,
5634         mbedtls_ssl_recv_t *f_recv,
5635         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
5636 {
5637     ssl->p_bio          = p_bio;
5638     ssl->f_send         = f_send;
5639     ssl->f_recv         = f_recv;
5640     ssl->f_recv_timeout = f_recv_timeout;
5641 }
5642 
mbedtls_ssl_conf_read_timeout(mbedtls_ssl_config * conf,uint32_t timeout)5643 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
5644 {
5645     conf->read_timeout   = timeout;
5646 }
5647 
mbedtls_ssl_set_timer_cb(mbedtls_ssl_context * ssl,void * p_timer,mbedtls_ssl_set_timer_t * f_set_timer,mbedtls_ssl_get_timer_t * f_get_timer)5648 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
5649                                void *p_timer,
5650                                mbedtls_ssl_set_timer_t *f_set_timer,
5651                                mbedtls_ssl_get_timer_t *f_get_timer )
5652 {
5653     ssl->p_timer        = p_timer;
5654     ssl->f_set_timer    = f_set_timer;
5655     ssl->f_get_timer    = f_get_timer;
5656 
5657     /* Make sure we start with no timer running */
5658     ssl_set_timer( ssl, 0 );
5659 }
5660 
5661 #if defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_session_cache(mbedtls_ssl_config * conf,void * p_cache,int (* f_get_cache)(void *,mbedtls_ssl_session *),int (* f_set_cache)(void *,const mbedtls_ssl_session *))5662 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
5663         void *p_cache,
5664         int (*f_get_cache)(void *, mbedtls_ssl_session *),
5665         int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
5666 {
5667     conf->p_cache = p_cache;
5668     conf->f_get_cache = f_get_cache;
5669     conf->f_set_cache = f_set_cache;
5670 }
5671 #endif /* MBEDTLS_SSL_SRV_C */
5672 
5673 #if defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_set_session(mbedtls_ssl_context * ssl,const mbedtls_ssl_session * session)5674 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
5675 {
5676     int ret;
5677 
5678     if( ssl == NULL ||
5679         session == NULL ||
5680         ssl->session_negotiate == NULL ||
5681         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
5682     {
5683         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5684     }
5685 
5686     if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
5687         return( ret );
5688 
5689     ssl->handshake->resume = 1;
5690 
5691     return( 0 );
5692 }
5693 #endif /* MBEDTLS_SSL_CLI_C */
5694 
mbedtls_ssl_conf_ciphersuites(mbedtls_ssl_config * conf,const int * ciphersuites)5695 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
5696                                    const int *ciphersuites )
5697 {
5698     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
5699     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
5700     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
5701     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
5702 }
5703 
mbedtls_ssl_conf_ciphersuites_for_version(mbedtls_ssl_config * conf,const int * ciphersuites,int major,int minor)5704 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
5705                                        const int *ciphersuites,
5706                                        int major, int minor )
5707 {
5708     if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
5709         return;
5710 
5711     if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
5712         return;
5713 
5714     conf->ciphersuite_list[minor] = ciphersuites;
5715 }
5716 
5717 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config * conf,const mbedtls_x509_crt_profile * profile)5718 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
5719                                     const mbedtls_x509_crt_profile *profile )
5720 {
5721     conf->cert_profile = profile;
5722 }
5723 
5724 /* Append a new keycert entry to a (possibly empty) list */
ssl_append_key_cert(mbedtls_ssl_key_cert ** head,mbedtls_x509_crt * cert,mbedtls_pk_context * key)5725 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
5726                                 mbedtls_x509_crt *cert,
5727                                 mbedtls_pk_context *key )
5728 {
5729     mbedtls_ssl_key_cert *new;
5730 
5731     new = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
5732     if( new == NULL )
5733         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5734 
5735     new->cert = cert;
5736     new->key  = key;
5737     new->next = NULL;
5738 
5739     /* Update head is the list was null, else add to the end */
5740     if( *head == NULL )
5741     {
5742         *head = new;
5743     }
5744     else
5745     {
5746         mbedtls_ssl_key_cert *cur = *head;
5747         while( cur->next != NULL )
5748             cur = cur->next;
5749         cur->next = new;
5750     }
5751 
5752     return( 0 );
5753 }
5754 
mbedtls_ssl_conf_own_cert(mbedtls_ssl_config * conf,mbedtls_x509_crt * own_cert,mbedtls_pk_context * pk_key)5755 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
5756                               mbedtls_x509_crt *own_cert,
5757                               mbedtls_pk_context *pk_key )
5758 {
5759     return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
5760 }
5761 
mbedtls_ssl_conf_ca_chain(mbedtls_ssl_config * conf,mbedtls_x509_crt * ca_chain,mbedtls_x509_crl * ca_crl)5762 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
5763                                mbedtls_x509_crt *ca_chain,
5764                                mbedtls_x509_crl *ca_crl )
5765 {
5766     conf->ca_chain   = ca_chain;
5767     conf->ca_crl     = ca_crl;
5768 }
5769 #endif /* MBEDTLS_X509_CRT_PARSE_C */
5770 
5771 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
mbedtls_ssl_set_hs_own_cert(mbedtls_ssl_context * ssl,mbedtls_x509_crt * own_cert,mbedtls_pk_context * pk_key)5772 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
5773                                  mbedtls_x509_crt *own_cert,
5774                                  mbedtls_pk_context *pk_key )
5775 {
5776     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
5777                                  own_cert, pk_key ) );
5778 }
5779 
mbedtls_ssl_set_hs_ca_chain(mbedtls_ssl_context * ssl,mbedtls_x509_crt * ca_chain,mbedtls_x509_crl * ca_crl)5780 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
5781                                   mbedtls_x509_crt *ca_chain,
5782                                   mbedtls_x509_crl *ca_crl )
5783 {
5784     ssl->handshake->sni_ca_chain   = ca_chain;
5785     ssl->handshake->sni_ca_crl     = ca_crl;
5786 }
5787 
mbedtls_ssl_set_hs_authmode(mbedtls_ssl_context * ssl,int authmode)5788 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
5789                                   int authmode )
5790 {
5791     ssl->handshake->sni_authmode = authmode;
5792 }
5793 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
5794 
5795 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5796 /*
5797  * Set EC J-PAKE password for current handshake
5798  */
mbedtls_ssl_set_hs_ecjpake_password(mbedtls_ssl_context * ssl,const unsigned char * pw,size_t pw_len)5799 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
5800                                          const unsigned char *pw,
5801                                          size_t pw_len )
5802 {
5803     mbedtls_ecjpake_role role;
5804 
5805     if( ssl->handshake == NULL || ssl->conf == NULL )
5806         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5807 
5808     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5809         role = MBEDTLS_ECJPAKE_SERVER;
5810     else
5811         role = MBEDTLS_ECJPAKE_CLIENT;
5812 
5813     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
5814                                    role,
5815                                    MBEDTLS_MD_SHA256,
5816                                    MBEDTLS_ECP_DP_SECP256R1,
5817                                    pw, pw_len ) );
5818 }
5819 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
5820 
5821 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
mbedtls_ssl_conf_psk(mbedtls_ssl_config * conf,const unsigned char * psk,size_t psk_len,const unsigned char * psk_identity,size_t psk_identity_len)5822 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
5823                 const unsigned char *psk, size_t psk_len,
5824                 const unsigned char *psk_identity, size_t psk_identity_len )
5825 {
5826     if( psk == NULL || psk_identity == NULL )
5827         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5828 
5829     if( psk_len > MBEDTLS_PSK_MAX_LEN )
5830         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5831 
5832     /* Identity len will be encoded on two bytes */
5833     if( ( psk_identity_len >> 16 ) != 0 ||
5834         psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN )
5835     {
5836         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5837     }
5838 
5839     if( conf->psk != NULL || conf->psk_identity != NULL )
5840     {
5841         mbedtls_free( conf->psk );
5842         mbedtls_free( conf->psk_identity );
5843         conf->psk = NULL;
5844         conf->psk_identity = NULL;
5845     }
5846 
5847     if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
5848         ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
5849     {
5850         mbedtls_free( conf->psk );
5851         mbedtls_free( conf->psk_identity );
5852         conf->psk = NULL;
5853         conf->psk_identity = NULL;
5854         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5855     }
5856 
5857     conf->psk_len = psk_len;
5858     conf->psk_identity_len = psk_identity_len;
5859 
5860     memcpy( conf->psk, psk, conf->psk_len );
5861     memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
5862 
5863     return( 0 );
5864 }
5865 
mbedtls_ssl_set_hs_psk(mbedtls_ssl_context * ssl,const unsigned char * psk,size_t psk_len)5866 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
5867                             const unsigned char *psk, size_t psk_len )
5868 {
5869     if( psk == NULL || ssl->handshake == NULL )
5870         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5871 
5872     if( psk_len > MBEDTLS_PSK_MAX_LEN )
5873         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5874 
5875     if( ssl->handshake->psk != NULL )
5876         mbedtls_free( ssl->handshake->psk );
5877 
5878     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
5879         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5880 
5881     ssl->handshake->psk_len = psk_len;
5882     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
5883 
5884     return( 0 );
5885 }
5886 
mbedtls_ssl_conf_psk_cb(mbedtls_ssl_config * conf,int (* f_psk)(void *,mbedtls_ssl_context *,const unsigned char *,size_t),void * p_psk)5887 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
5888                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
5889                      size_t),
5890                      void *p_psk )
5891 {
5892     conf->f_psk = f_psk;
5893     conf->p_psk = p_psk;
5894 }
5895 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
5896 
5897 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_dh_param(mbedtls_ssl_config * conf,const char * dhm_P,const char * dhm_G)5898 int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
5899 {
5900     int ret;
5901 
5902     if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
5903         ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
5904     {
5905         mbedtls_mpi_free( &conf->dhm_P );
5906         mbedtls_mpi_free( &conf->dhm_G );
5907         return( ret );
5908     }
5909 
5910     return( 0 );
5911 }
5912 
mbedtls_ssl_conf_dh_param_ctx(mbedtls_ssl_config * conf,mbedtls_dhm_context * dhm_ctx)5913 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
5914 {
5915     int ret;
5916 
5917     if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
5918         ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
5919     {
5920         mbedtls_mpi_free( &conf->dhm_P );
5921         mbedtls_mpi_free( &conf->dhm_G );
5922         return( ret );
5923     }
5924 
5925     return( 0 );
5926 }
5927 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
5928 
5929 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
5930 /*
5931  * Set the minimum length for Diffie-Hellman parameters
5932  */
mbedtls_ssl_conf_dhm_min_bitlen(mbedtls_ssl_config * conf,unsigned int bitlen)5933 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
5934                                       unsigned int bitlen )
5935 {
5936     conf->dhm_min_bitlen = bitlen;
5937 }
5938 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
5939 
5940 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
5941 /*
5942  * Set allowed/preferred hashes for handshake signatures
5943  */
mbedtls_ssl_conf_sig_hashes(mbedtls_ssl_config * conf,const int * hashes)5944 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
5945                                   const int *hashes )
5946 {
5947     conf->sig_hashes = hashes;
5948 }
5949 #endif
5950 
5951 #if defined(MBEDTLS_ECP_C)
5952 /*
5953  * Set the allowed elliptic curves
5954  */
mbedtls_ssl_conf_curves(mbedtls_ssl_config * conf,const mbedtls_ecp_group_id * curve_list)5955 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
5956                              const mbedtls_ecp_group_id *curve_list )
5957 {
5958     conf->curve_list = curve_list;
5959 }
5960 #endif
5961 
5962 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_set_hostname(mbedtls_ssl_context * ssl,const char * hostname)5963 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
5964 {
5965     size_t hostname_len;
5966 
5967     if( hostname == NULL )
5968         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5969 
5970     hostname_len = strlen( hostname );
5971 
5972     if( hostname_len + 1 == 0 )
5973         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5974 
5975     if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
5976         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
5977 
5978     ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
5979 
5980     if( ssl->hostname == NULL )
5981         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5982 
5983     memcpy( ssl->hostname, hostname, hostname_len );
5984 
5985     ssl->hostname[hostname_len] = '\0';
5986 
5987     return( 0 );
5988 }
5989 #endif
5990 
5991 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
mbedtls_ssl_conf_sni(mbedtls_ssl_config * conf,int (* f_sni)(void *,mbedtls_ssl_context *,const unsigned char *,size_t),void * p_sni)5992 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
5993                   int (*f_sni)(void *, mbedtls_ssl_context *,
5994                                 const unsigned char *, size_t),
5995                   void *p_sni )
5996 {
5997     conf->f_sni = f_sni;
5998     conf->p_sni = p_sni;
5999 }
6000 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
6001 
6002 #if defined(MBEDTLS_SSL_ALPN)
mbedtls_ssl_conf_alpn_protocols(mbedtls_ssl_config * conf,const char ** protos)6003 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
6004 {
6005     size_t cur_len, tot_len;
6006     const char **p;
6007 
6008     /*
6009      * "Empty strings MUST NOT be included and byte strings MUST NOT be
6010      * truncated". Check lengths now rather than later.
6011      */
6012     tot_len = 0;
6013     for( p = protos; *p != NULL; p++ )
6014     {
6015         cur_len = strlen( *p );
6016         tot_len += cur_len;
6017 
6018         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
6019             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6020     }
6021 
6022     conf->alpn_list = protos;
6023 
6024     return( 0 );
6025 }
6026 
mbedtls_ssl_get_alpn_protocol(const mbedtls_ssl_context * ssl)6027 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
6028 {
6029     return( ssl->alpn_chosen );
6030 }
6031 #endif /* MBEDTLS_SSL_ALPN */
6032 
mbedtls_ssl_conf_max_version(mbedtls_ssl_config * conf,int major,int minor)6033 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
6034 {
6035     conf->max_major_ver = major;
6036     conf->max_minor_ver = minor;
6037 }
6038 
mbedtls_ssl_conf_min_version(mbedtls_ssl_config * conf,int major,int minor)6039 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
6040 {
6041     conf->min_major_ver = major;
6042     conf->min_minor_ver = minor;
6043 }
6044 
6045 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_conf_fallback(mbedtls_ssl_config * conf,char fallback)6046 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
6047 {
6048     conf->fallback = fallback;
6049 }
6050 #endif
6051 
6052 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
mbedtls_ssl_conf_encrypt_then_mac(mbedtls_ssl_config * conf,char etm)6053 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
6054 {
6055     conf->encrypt_then_mac = etm;
6056 }
6057 #endif
6058 
6059 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
mbedtls_ssl_conf_extended_master_secret(mbedtls_ssl_config * conf,char ems)6060 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
6061 {
6062     conf->extended_ms = ems;
6063 }
6064 #endif
6065 
6066 #if defined(MBEDTLS_ARC4_C)
mbedtls_ssl_conf_arc4_support(mbedtls_ssl_config * conf,char arc4)6067 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
6068 {
6069     conf->arc4_disabled = arc4;
6070 }
6071 #endif
6072 
6073 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
mbedtls_ssl_conf_max_frag_len(mbedtls_ssl_config * conf,unsigned char mfl_code)6074 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
6075 {
6076     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
6077         mfl_code_to_length[mfl_code] > MBEDTLS_SSL_MAX_CONTENT_LEN )
6078     {
6079         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6080     }
6081 
6082     conf->mfl_code = mfl_code;
6083 
6084     return( 0 );
6085 }
6086 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6087 
6088 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
mbedtls_ssl_conf_truncated_hmac(mbedtls_ssl_config * conf,int truncate)6089 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
6090 {
6091     conf->trunc_hmac = truncate;
6092 }
6093 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
6094 
6095 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
mbedtls_ssl_conf_cbc_record_splitting(mbedtls_ssl_config * conf,char split)6096 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
6097 {
6098     conf->cbc_record_splitting = split;
6099 }
6100 #endif
6101 
mbedtls_ssl_conf_legacy_renegotiation(mbedtls_ssl_config * conf,int allow_legacy)6102 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
6103 {
6104     conf->allow_legacy_renegotiation = allow_legacy;
6105 }
6106 
6107 #if defined(MBEDTLS_SSL_RENEGOTIATION)
mbedtls_ssl_conf_renegotiation(mbedtls_ssl_config * conf,int renegotiation)6108 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
6109 {
6110     conf->disable_renegotiation = renegotiation;
6111 }
6112 
mbedtls_ssl_conf_renegotiation_enforced(mbedtls_ssl_config * conf,int max_records)6113 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
6114 {
6115     conf->renego_max_records = max_records;
6116 }
6117 
mbedtls_ssl_conf_renegotiation_period(mbedtls_ssl_config * conf,const unsigned char period[8])6118 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
6119                                    const unsigned char period[8] )
6120 {
6121     memcpy( conf->renego_period, period, 8 );
6122 }
6123 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6124 
6125 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
6126 #if defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_conf_session_tickets(mbedtls_ssl_config * conf,int use_tickets)6127 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
6128 {
6129     conf->session_tickets = use_tickets;
6130 }
6131 #endif
6132 
6133 #if defined(MBEDTLS_SSL_SRV_C)
mbedtls_ssl_conf_session_tickets_cb(mbedtls_ssl_config * conf,mbedtls_ssl_ticket_write_t * f_ticket_write,mbedtls_ssl_ticket_parse_t * f_ticket_parse,void * p_ticket)6134 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
6135         mbedtls_ssl_ticket_write_t *f_ticket_write,
6136         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
6137         void *p_ticket )
6138 {
6139     conf->f_ticket_write = f_ticket_write;
6140     conf->f_ticket_parse = f_ticket_parse;
6141     conf->p_ticket       = p_ticket;
6142 }
6143 #endif
6144 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
6145 
6146 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
mbedtls_ssl_conf_export_keys_cb(mbedtls_ssl_config * conf,mbedtls_ssl_export_keys_t * f_export_keys,void * p_export_keys)6147 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
6148         mbedtls_ssl_export_keys_t *f_export_keys,
6149         void *p_export_keys )
6150 {
6151     conf->f_export_keys = f_export_keys;
6152     conf->p_export_keys = p_export_keys;
6153 }
6154 #endif
6155 
6156 /*
6157  * SSL get accessors
6158  */
mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context * ssl)6159 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
6160 {
6161     return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
6162 }
6163 
mbedtls_ssl_get_verify_result(const mbedtls_ssl_context * ssl)6164 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
6165 {
6166     if( ssl->session != NULL )
6167         return( ssl->session->verify_result );
6168 
6169     if( ssl->session_negotiate != NULL )
6170         return( ssl->session_negotiate->verify_result );
6171 
6172     return( 0xFFFFFFFF );
6173 }
6174 
mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context * ssl)6175 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
6176 {
6177     if( ssl == NULL || ssl->session == NULL )
6178         return( NULL );
6179 
6180     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
6181 }
6182 
mbedtls_ssl_get_version(const mbedtls_ssl_context * ssl)6183 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
6184 {
6185 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6186     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6187     {
6188         switch( ssl->minor_ver )
6189         {
6190             case MBEDTLS_SSL_MINOR_VERSION_2:
6191                 return( "DTLSv1.0" );
6192 
6193             case MBEDTLS_SSL_MINOR_VERSION_3:
6194                 return( "DTLSv1.2" );
6195 
6196             default:
6197                 return( "unknown (DTLS)" );
6198         }
6199     }
6200 #endif
6201 
6202     switch( ssl->minor_ver )
6203     {
6204         case MBEDTLS_SSL_MINOR_VERSION_0:
6205             return( "SSLv3.0" );
6206 
6207         case MBEDTLS_SSL_MINOR_VERSION_1:
6208             return( "TLSv1.0" );
6209 
6210         case MBEDTLS_SSL_MINOR_VERSION_2:
6211             return( "TLSv1.1" );
6212 
6213         case MBEDTLS_SSL_MINOR_VERSION_3:
6214             return( "TLSv1.2" );
6215 
6216         default:
6217             return( "unknown" );
6218     }
6219 }
6220 
mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context * ssl)6221 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
6222 {
6223     size_t transform_expansion;
6224     const mbedtls_ssl_transform *transform = ssl->transform_out;
6225 
6226 #if defined(MBEDTLS_ZLIB_SUPPORT)
6227     if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
6228         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
6229 #endif
6230 
6231     if( transform == NULL )
6232         return( (int) mbedtls_ssl_hdr_len( ssl ) );
6233 
6234     switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
6235     {
6236         case MBEDTLS_MODE_GCM:
6237         case MBEDTLS_MODE_CCM:
6238         case MBEDTLS_MODE_STREAM:
6239             transform_expansion = transform->minlen;
6240             break;
6241 
6242         case MBEDTLS_MODE_CBC:
6243             transform_expansion = transform->maclen
6244                       + mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc );
6245             break;
6246 
6247         default:
6248             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6249             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6250     }
6251 
6252     return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
6253 }
6254 
6255 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
mbedtls_ssl_get_max_frag_len(const mbedtls_ssl_context * ssl)6256 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
6257 {
6258     size_t max_len;
6259 
6260     /*
6261      * Assume mfl_code is correct since it was checked when set
6262      */
6263     max_len = mfl_code_to_length[ssl->conf->mfl_code];
6264 
6265     /*
6266      * Check if a smaller max length was negotiated
6267      */
6268     if( ssl->session_out != NULL &&
6269         mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
6270     {
6271         max_len = mfl_code_to_length[ssl->session_out->mfl_code];
6272     }
6273 
6274     return max_len;
6275 }
6276 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6277 
6278 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_get_peer_cert(const mbedtls_ssl_context * ssl)6279 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
6280 {
6281     if( ssl == NULL || ssl->session == NULL )
6282         return( NULL );
6283 
6284     return( ssl->session->peer_cert );
6285 }
6286 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6287 
6288 #if defined(MBEDTLS_SSL_CLI_C)
mbedtls_ssl_get_session(const mbedtls_ssl_context * ssl,mbedtls_ssl_session * dst)6289 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
6290 {
6291     if( ssl == NULL ||
6292         dst == NULL ||
6293         ssl->session == NULL ||
6294         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
6295     {
6296         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6297     }
6298 
6299     return( ssl_session_copy( dst, ssl->session ) );
6300 }
6301 #endif /* MBEDTLS_SSL_CLI_C */
6302 
6303 /*
6304  * Perform a single step of the SSL handshake
6305  */
mbedtls_ssl_handshake_step(mbedtls_ssl_context * ssl)6306 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
6307 {
6308     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6309 
6310     if( ssl == NULL || ssl->conf == NULL )
6311         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6312 
6313 #if defined(MBEDTLS_SSL_CLI_C)
6314     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6315         ret = mbedtls_ssl_handshake_client_step( ssl );
6316 #endif
6317 #if defined(MBEDTLS_SSL_SRV_C)
6318     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6319         ret = mbedtls_ssl_handshake_server_step( ssl );
6320 #endif
6321 
6322     return( ret );
6323 }
6324 
6325 /*
6326  * Perform the SSL handshake
6327  */
mbedtls_ssl_handshake(mbedtls_ssl_context * ssl)6328 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
6329 {
6330     int ret = 0;
6331 
6332     if( ssl == NULL || ssl->conf == NULL )
6333         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6334 
6335     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
6336 
6337     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6338     {
6339         ret = mbedtls_ssl_handshake_step( ssl );
6340 
6341         if( ret != 0 )
6342             break;
6343     }
6344 
6345     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
6346 
6347     return( ret );
6348 }
6349 
6350 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6351 #if defined(MBEDTLS_SSL_SRV_C)
6352 /*
6353  * Write HelloRequest to request renegotiation on server
6354  */
ssl_write_hello_request(mbedtls_ssl_context * ssl)6355 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
6356 {
6357     int ret;
6358 
6359     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
6360 
6361     ssl->out_msglen  = 4;
6362     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
6363     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
6364 
6365     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
6366     {
6367         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
6368         return( ret );
6369     }
6370 
6371     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
6372 
6373     return( 0 );
6374 }
6375 #endif /* MBEDTLS_SSL_SRV_C */
6376 
6377 /*
6378  * Actually renegotiate current connection, triggered by either:
6379  * - any side: calling mbedtls_ssl_renegotiate(),
6380  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
6381  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
6382  *   the initial handshake is completed.
6383  * If the handshake doesn't complete due to waiting for I/O, it will continue
6384  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
6385  */
ssl_start_renegotiation(mbedtls_ssl_context * ssl)6386 static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
6387 {
6388     int ret;
6389 
6390     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
6391 
6392     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
6393         return( ret );
6394 
6395     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
6396      * the ServerHello will have message_seq = 1" */
6397 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6398     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6399         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6400     {
6401         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6402             ssl->handshake->out_msg_seq = 1;
6403         else
6404             ssl->handshake->in_msg_seq = 1;
6405     }
6406 #endif
6407 
6408     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
6409     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
6410 
6411     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6412     {
6413         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6414         return( ret );
6415     }
6416 
6417     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
6418 
6419     return( 0 );
6420 }
6421 
6422 /*
6423  * Renegotiate current connection on client,
6424  * or request renegotiation on server
6425  */
mbedtls_ssl_renegotiate(mbedtls_ssl_context * ssl)6426 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
6427 {
6428     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6429 
6430     if( ssl == NULL || ssl->conf == NULL )
6431         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6432 
6433 #if defined(MBEDTLS_SSL_SRV_C)
6434     /* On server, just send the request */
6435     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6436     {
6437         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6438             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6439 
6440         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6441 
6442         /* Did we already try/start sending HelloRequest? */
6443         if( ssl->out_left != 0 )
6444             return( mbedtls_ssl_flush_output( ssl ) );
6445 
6446         return( ssl_write_hello_request( ssl ) );
6447     }
6448 #endif /* MBEDTLS_SSL_SRV_C */
6449 
6450 #if defined(MBEDTLS_SSL_CLI_C)
6451     /*
6452      * On client, either start the renegotiation process or,
6453      * if already in progress, continue the handshake
6454      */
6455     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
6456     {
6457         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6458             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6459 
6460         if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
6461         {
6462             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6463             return( ret );
6464         }
6465     }
6466     else
6467     {
6468         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6469         {
6470             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6471             return( ret );
6472         }
6473     }
6474 #endif /* MBEDTLS_SSL_CLI_C */
6475 
6476     return( ret );
6477 }
6478 
6479 /*
6480  * Check record counters and renegotiate if they're above the limit.
6481  */
ssl_check_ctr_renegotiate(mbedtls_ssl_context * ssl)6482 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
6483 {
6484     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
6485         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
6486         ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
6487     {
6488         return( 0 );
6489     }
6490 
6491     if( memcmp( ssl->in_ctr,  ssl->conf->renego_period, 8 ) <= 0 &&
6492         memcmp( ssl->out_ctr, ssl->conf->renego_period, 8 ) <= 0 )
6493     {
6494         return( 0 );
6495     }
6496 
6497     MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
6498     return( mbedtls_ssl_renegotiate( ssl ) );
6499 }
6500 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6501 
6502 /*
6503  * Receive application data decrypted from the SSL layer
6504  */
mbedtls_ssl_read(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)6505 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
6506 {
6507     int ret, record_read = 0;
6508     size_t n;
6509 
6510     if( ssl == NULL || ssl->conf == NULL )
6511         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6512 
6513     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
6514 
6515 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6516     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6517     {
6518         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
6519             return( ret );
6520 
6521         if( ssl->handshake != NULL &&
6522             ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
6523         {
6524             if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
6525                 return( ret );
6526         }
6527     }
6528 #endif
6529 
6530 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6531     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
6532     {
6533         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
6534         return( ret );
6535     }
6536 #endif
6537 
6538     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6539     {
6540         ret = mbedtls_ssl_handshake( ssl );
6541         if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
6542         {
6543             record_read = 1;
6544         }
6545         else if( ret != 0 )
6546         {
6547             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6548             return( ret );
6549         }
6550     }
6551 
6552     if( ssl->in_offt == NULL )
6553     {
6554         /* Start timer if not already running */
6555         if( ssl->f_get_timer != NULL &&
6556             ssl->f_get_timer( ssl->p_timer ) == -1 )
6557         {
6558             ssl_set_timer( ssl, ssl->conf->read_timeout );
6559         }
6560 
6561         if( ! record_read )
6562         {
6563             if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
6564             {
6565                 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
6566                     return( 0 );
6567 
6568                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
6569                 return( ret );
6570             }
6571         }
6572 
6573         if( ssl->in_msglen  == 0 &&
6574             ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
6575         {
6576             /*
6577              * OpenSSL sends empty messages to randomize the IV
6578              */
6579             if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
6580             {
6581                 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
6582                     return( 0 );
6583 
6584                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
6585                 return( ret );
6586             }
6587         }
6588 
6589 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6590         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
6591         {
6592             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
6593 
6594 #if defined(MBEDTLS_SSL_CLI_C)
6595             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
6596                 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
6597                   ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) )
6598             {
6599                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
6600 
6601                 /* With DTLS, drop the packet (probably from last handshake) */
6602 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6603                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6604                     return( MBEDTLS_ERR_SSL_WANT_READ );
6605 #endif
6606                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6607             }
6608 
6609             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
6610                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
6611             {
6612                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
6613 
6614                 /* With DTLS, drop the packet (probably from last handshake) */
6615 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6616                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6617                     return( MBEDTLS_ERR_SSL_WANT_READ );
6618 #endif
6619                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6620             }
6621 #endif
6622 
6623             if( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
6624                 ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
6625                   ssl->conf->allow_legacy_renegotiation ==
6626                                                 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) )
6627             {
6628                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
6629 
6630 #if defined(MBEDTLS_SSL_PROTO_SSL3)
6631                 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
6632                 {
6633                     /*
6634                      * SSLv3 does not have a "no_renegotiation" alert
6635                      */
6636                     if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
6637                         return( ret );
6638                 }
6639                 else
6640 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
6641 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
6642     defined(MBEDTLS_SSL_PROTO_TLS1_2)
6643                 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
6644                 {
6645                     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
6646                                     MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6647                                     MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
6648                     {
6649                         return( ret );
6650                     }
6651                 }
6652                 else
6653 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
6654           MBEDTLS_SSL_PROTO_TLS1_2 */
6655                 {
6656                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6657                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6658                 }
6659             }
6660             else
6661             {
6662                 /* DTLS clients need to know renego is server-initiated */
6663 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6664                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6665                     ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6666                 {
6667                     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6668                 }
6669 #endif
6670                 ret = ssl_start_renegotiation( ssl );
6671                 if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO )
6672                 {
6673                     record_read = 1;
6674                 }
6675                 else if( ret != 0 )
6676                 {
6677                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6678                     return( ret );
6679                 }
6680             }
6681 
6682             /* If a non-handshake record was read during renego, fallthrough,
6683              * else tell the user they should call mbedtls_ssl_read() again */
6684             if( ! record_read )
6685                 return( MBEDTLS_ERR_SSL_WANT_READ );
6686         }
6687         else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6688         {
6689 
6690             if( ssl->conf->renego_max_records >= 0 )
6691             {
6692                 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
6693                 {
6694                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
6695                                         "but not honored by client" ) );
6696                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6697                 }
6698             }
6699         }
6700 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6701 
6702         /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
6703         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
6704         {
6705             MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
6706             return( MBEDTLS_ERR_SSL_WANT_READ );
6707         }
6708 
6709         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
6710         {
6711             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
6712             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
6713         }
6714 
6715         ssl->in_offt = ssl->in_msg;
6716 
6717         /* We're going to return something now, cancel timer,
6718          * except if handshake (renegotiation) is in progress */
6719         if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
6720             ssl_set_timer( ssl, 0 );
6721 
6722 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6723         /* If we requested renego but received AppData, resend HelloRequest.
6724          * Do it now, after setting in_offt, to avoid taking this branch
6725          * again if ssl_write_hello_request() returns WANT_WRITE */
6726 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
6727         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
6728             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6729         {
6730             if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
6731             {
6732                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
6733                 return( ret );
6734             }
6735         }
6736 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
6737 #endif
6738     }
6739 
6740     n = ( len < ssl->in_msglen )
6741         ? len : ssl->in_msglen;
6742 
6743     memcpy( buf, ssl->in_offt, n );
6744     ssl->in_msglen -= n;
6745 
6746     if( ssl->in_msglen == 0 )
6747         /* all bytes consumed  */
6748         ssl->in_offt = NULL;
6749     else
6750         /* more data available */
6751         ssl->in_offt += n;
6752 
6753     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
6754 
6755     return( (int) n );
6756 }
6757 
6758 /*
6759  * Send application data to be encrypted by the SSL layer,
6760  * taking care of max fragment length and buffer size
6761  */
ssl_write_real(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)6762 static int ssl_write_real( mbedtls_ssl_context *ssl,
6763                            const unsigned char *buf, size_t len )
6764 {
6765     int ret;
6766 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6767     size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );
6768 
6769     if( len > max_len )
6770     {
6771 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6772         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6773         {
6774             MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
6775                                 "maximum fragment length: %d > %d",
6776                                 len, max_len ) );
6777             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6778         }
6779         else
6780 #endif
6781             len = max_len;
6782     }
6783 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6784 
6785     if( ssl->out_left != 0 )
6786     {
6787         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
6788         {
6789             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
6790             return( ret );
6791         }
6792     }
6793     else
6794     {
6795         ssl->out_msglen  = len;
6796         ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
6797         memcpy( ssl->out_msg, buf, len );
6798 
6799         if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
6800         {
6801             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
6802             return( ret );
6803         }
6804     }
6805 
6806     return( (int) len );
6807 }
6808 
6809 /*
6810  * Write application data, doing 1/n-1 splitting if necessary.
6811  *
6812  * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
6813  * then the caller will call us again with the same arguments, so
6814  * remember wether we already did the split or not.
6815  */
6816 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
ssl_write_split(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)6817 static int ssl_write_split( mbedtls_ssl_context *ssl,
6818                             const unsigned char *buf, size_t len )
6819 {
6820     int ret;
6821 
6822     if( ssl->conf->cbc_record_splitting ==
6823             MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
6824         len <= 1 ||
6825         ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
6826         mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
6827                                 != MBEDTLS_MODE_CBC )
6828     {
6829         return( ssl_write_real( ssl, buf, len ) );
6830     }
6831 
6832     if( ssl->split_done == 0 )
6833     {
6834         if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
6835             return( ret );
6836         ssl->split_done = 1;
6837     }
6838 
6839     if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
6840         return( ret );
6841     ssl->split_done = 0;
6842 
6843     return( ret + 1 );
6844 }
6845 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
6846 
6847 /*
6848  * Write application data (public-facing wrapper)
6849  */
mbedtls_ssl_write(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)6850 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
6851 {
6852     int ret;
6853 
6854     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
6855 
6856     if( ssl == NULL || ssl->conf == NULL )
6857         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6858 
6859 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6860     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
6861     {
6862         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
6863         return( ret );
6864     }
6865 #endif
6866 
6867     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6868     {
6869         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6870         {
6871             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6872             return( ret );
6873         }
6874     }
6875 
6876 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6877     ret = ssl_write_split( ssl, buf, len );
6878 #else
6879     ret = ssl_write_real( ssl, buf, len );
6880 #endif
6881 
6882     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
6883 
6884     return( ret );
6885 }
6886 
6887 /*
6888  * Notify the peer that the connection is being closed
6889  */
mbedtls_ssl_close_notify(mbedtls_ssl_context * ssl)6890 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
6891 {
6892     int ret;
6893 
6894     if( ssl == NULL || ssl->conf == NULL )
6895         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6896 
6897     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
6898 
6899     if( ssl->out_left != 0 )
6900         return( mbedtls_ssl_flush_output( ssl ) );
6901 
6902     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
6903     {
6904         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
6905                         MBEDTLS_SSL_ALERT_LEVEL_WARNING,
6906                         MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
6907         {
6908             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
6909             return( ret );
6910         }
6911     }
6912 
6913     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
6914 
6915     return( 0 );
6916 }
6917 
mbedtls_ssl_transform_free(mbedtls_ssl_transform * transform)6918 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
6919 {
6920     if( transform == NULL )
6921         return;
6922 
6923 #if defined(MBEDTLS_ZLIB_SUPPORT)
6924     deflateEnd( &transform->ctx_deflate );
6925     inflateEnd( &transform->ctx_inflate );
6926 #endif
6927 
6928     mbedtls_cipher_free( &transform->cipher_ctx_enc );
6929     mbedtls_cipher_free( &transform->cipher_ctx_dec );
6930 
6931     mbedtls_md_free( &transform->md_ctx_enc );
6932     mbedtls_md_free( &transform->md_ctx_dec );
6933 
6934     mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
6935 }
6936 
6937 #if defined(MBEDTLS_X509_CRT_PARSE_C)
ssl_key_cert_free(mbedtls_ssl_key_cert * key_cert)6938 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
6939 {
6940     mbedtls_ssl_key_cert *cur = key_cert, *next;
6941 
6942     while( cur != NULL )
6943     {
6944         next = cur->next;
6945         mbedtls_free( cur );
6946         cur = next;
6947     }
6948 }
6949 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6950 
mbedtls_ssl_handshake_free(mbedtls_ssl_handshake_params * handshake)6951 void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake )
6952 {
6953     if( handshake == NULL )
6954         return;
6955 
6956 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
6957     defined(MBEDTLS_SSL_PROTO_TLS1_1)
6958     mbedtls_md5_free(    &handshake->fin_md5  );
6959     mbedtls_sha1_free(   &handshake->fin_sha1 );
6960 #endif
6961 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
6962 #if defined(MBEDTLS_SHA256_C)
6963     mbedtls_sha256_free(   &handshake->fin_sha256    );
6964 #endif
6965 #if defined(MBEDTLS_SHA512_C)
6966     mbedtls_sha512_free(   &handshake->fin_sha512    );
6967 #endif
6968 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
6969 
6970 #if defined(MBEDTLS_DHM_C)
6971     mbedtls_dhm_free( &handshake->dhm_ctx );
6972 #endif
6973 #if defined(MBEDTLS_ECDH_C)
6974     mbedtls_ecdh_free( &handshake->ecdh_ctx );
6975 #endif
6976 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
6977     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
6978 #if defined(MBEDTLS_SSL_CLI_C)
6979     mbedtls_free( handshake->ecjpake_cache );
6980     handshake->ecjpake_cache = NULL;
6981     handshake->ecjpake_cache_len = 0;
6982 #endif
6983 #endif
6984 
6985 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
6986     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
6987     /* explicit void pointer cast for buggy MS compiler */
6988     mbedtls_free( (void *) handshake->curves );
6989 #endif
6990 
6991 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
6992     if( handshake->psk != NULL )
6993     {
6994         mbedtls_zeroize( handshake->psk, handshake->psk_len );
6995         mbedtls_free( handshake->psk );
6996     }
6997 #endif
6998 
6999 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
7000     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
7001     /*
7002      * Free only the linked list wrapper, not the keys themselves
7003      * since the belong to the SNI callback
7004      */
7005     if( handshake->sni_key_cert != NULL )
7006     {
7007         mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
7008 
7009         while( cur != NULL )
7010         {
7011             next = cur->next;
7012             mbedtls_free( cur );
7013             cur = next;
7014         }
7015     }
7016 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
7017 
7018 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7019     mbedtls_free( handshake->verify_cookie );
7020     mbedtls_free( handshake->hs_msg );
7021     ssl_flight_free( handshake->flight );
7022 #endif
7023 
7024     mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) );
7025 }
7026 
mbedtls_ssl_session_free(mbedtls_ssl_session * session)7027 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
7028 {
7029     if( session == NULL )
7030         return;
7031 
7032 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7033     if( session->peer_cert != NULL )
7034     {
7035         mbedtls_x509_crt_free( session->peer_cert );
7036         mbedtls_free( session->peer_cert );
7037     }
7038 #endif
7039 
7040 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
7041     mbedtls_free( session->ticket );
7042 #endif
7043 
7044     mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) );
7045 }
7046 
7047 /*
7048  * Free an SSL context
7049  */
mbedtls_ssl_free(mbedtls_ssl_context * ssl)7050 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
7051 {
7052     if( ssl == NULL )
7053         return;
7054 
7055     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
7056 
7057     if( ssl->out_buf != NULL )
7058     {
7059         mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN );
7060         mbedtls_free( ssl->out_buf );
7061     }
7062 
7063     if( ssl->in_buf != NULL )
7064     {
7065         mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN );
7066         mbedtls_free( ssl->in_buf );
7067     }
7068 
7069 #if defined(MBEDTLS_ZLIB_SUPPORT)
7070     if( ssl->compress_buf != NULL )
7071     {
7072         mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN );
7073         mbedtls_free( ssl->compress_buf );
7074     }
7075 #endif
7076 
7077     if( ssl->transform )
7078     {
7079         mbedtls_ssl_transform_free( ssl->transform );
7080         mbedtls_free( ssl->transform );
7081     }
7082 
7083     if( ssl->handshake )
7084     {
7085         mbedtls_ssl_handshake_free( ssl->handshake );
7086         mbedtls_ssl_transform_free( ssl->transform_negotiate );
7087         mbedtls_ssl_session_free( ssl->session_negotiate );
7088 
7089         mbedtls_free( ssl->handshake );
7090         mbedtls_free( ssl->transform_negotiate );
7091         mbedtls_free( ssl->session_negotiate );
7092     }
7093 
7094     if( ssl->session )
7095     {
7096         mbedtls_ssl_session_free( ssl->session );
7097         mbedtls_free( ssl->session );
7098     }
7099 
7100 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7101     if( ssl->hostname != NULL )
7102     {
7103         mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) );
7104         mbedtls_free( ssl->hostname );
7105     }
7106 #endif
7107 
7108 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
7109     if( mbedtls_ssl_hw_record_finish != NULL )
7110     {
7111         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
7112         mbedtls_ssl_hw_record_finish( ssl );
7113     }
7114 #endif
7115 
7116 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7117     mbedtls_free( ssl->cli_id );
7118 #endif
7119 
7120     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
7121 
7122     /* Actually clear after last debug message */
7123     mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
7124 }
7125 
7126 /*
7127  * Initialze mbedtls_ssl_config
7128  */
mbedtls_ssl_config_init(mbedtls_ssl_config * conf)7129 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
7130 {
7131     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
7132 }
7133 
7134 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7135 static int ssl_preset_default_hashes[] = {
7136 #if defined(MBEDTLS_SHA512_C)
7137     MBEDTLS_MD_SHA512,
7138     MBEDTLS_MD_SHA384,
7139 #endif
7140 #if defined(MBEDTLS_SHA256_C)
7141     MBEDTLS_MD_SHA256,
7142     MBEDTLS_MD_SHA224,
7143 #endif
7144 #if defined(MBEDTLS_SHA1_C)
7145     MBEDTLS_MD_SHA1,
7146 #endif
7147     MBEDTLS_MD_NONE
7148 };
7149 #endif
7150 
7151 static int ssl_preset_suiteb_ciphersuites[] = {
7152     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
7153     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
7154     0
7155 };
7156 
7157 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7158 static int ssl_preset_suiteb_hashes[] = {
7159     MBEDTLS_MD_SHA256,
7160     MBEDTLS_MD_SHA384,
7161     MBEDTLS_MD_NONE
7162 };
7163 #endif
7164 
7165 #if defined(MBEDTLS_ECP_C)
7166 static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
7167     MBEDTLS_ECP_DP_SECP256R1,
7168     MBEDTLS_ECP_DP_SECP384R1,
7169     MBEDTLS_ECP_DP_NONE
7170 };
7171 #endif
7172 
7173 /*
7174  * Load default in mbedtls_ssl_config
7175  */
mbedtls_ssl_config_defaults(mbedtls_ssl_config * conf,int endpoint,int transport,int preset)7176 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
7177                                  int endpoint, int transport, int preset )
7178 {
7179 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7180     int ret;
7181 #endif
7182 
7183     /* Use the functions here so that they are covered in tests,
7184      * but otherwise access member directly for efficiency */
7185     mbedtls_ssl_conf_endpoint( conf, endpoint );
7186     mbedtls_ssl_conf_transport( conf, transport );
7187 
7188     /*
7189      * Things that are common to all presets
7190      */
7191 #if defined(MBEDTLS_SSL_CLI_C)
7192     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
7193     {
7194         conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
7195 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
7196         conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
7197 #endif
7198     }
7199 #endif
7200 
7201 #if defined(MBEDTLS_ARC4_C)
7202     conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
7203 #endif
7204 
7205 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
7206     conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
7207 #endif
7208 
7209 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
7210     conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
7211 #endif
7212 
7213 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7214     conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
7215 #endif
7216 
7217 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7218     conf->f_cookie_write = ssl_cookie_write_dummy;
7219     conf->f_cookie_check = ssl_cookie_check_dummy;
7220 #endif
7221 
7222 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
7223     conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
7224 #endif
7225 
7226 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7227     conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
7228     conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
7229 #endif
7230 
7231 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7232     conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
7233     memset( conf->renego_period, 0xFF, 7 );
7234     conf->renego_period[7] = 0x00;
7235 #endif
7236 
7237 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7238             if( endpoint == MBEDTLS_SSL_IS_SERVER )
7239             {
7240                 if( ( ret = mbedtls_ssl_conf_dh_param( conf,
7241                                 MBEDTLS_DHM_RFC5114_MODP_2048_P,
7242                                 MBEDTLS_DHM_RFC5114_MODP_2048_G ) ) != 0 )
7243                 {
7244                     return( ret );
7245                 }
7246             }
7247 #endif
7248 
7249     /*
7250      * Preset-specific defaults
7251      */
7252     switch( preset )
7253     {
7254         /*
7255          * NSA Suite B
7256          */
7257         case MBEDTLS_SSL_PRESET_SUITEB:
7258             conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7259             conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
7260             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7261             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7262 
7263             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7264             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7265             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7266             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7267                                    ssl_preset_suiteb_ciphersuites;
7268 
7269 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7270             conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
7271 #endif
7272 
7273 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7274             conf->sig_hashes = ssl_preset_suiteb_hashes;
7275 #endif
7276 
7277 #if defined(MBEDTLS_ECP_C)
7278             conf->curve_list = ssl_preset_suiteb_curves;
7279 #endif
7280             break;
7281 
7282         /*
7283          * Default
7284          */
7285         default:
7286             conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7287             conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS 1.0 */
7288             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7289             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7290 
7291 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7292             if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7293                 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
7294 #endif
7295 
7296             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7297             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7298             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7299             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7300                                    mbedtls_ssl_list_ciphersuites();
7301 
7302 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7303             conf->cert_profile = &mbedtls_x509_crt_profile_default;
7304 #endif
7305 
7306 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7307             conf->sig_hashes = ssl_preset_default_hashes;
7308 #endif
7309 
7310 #if defined(MBEDTLS_ECP_C)
7311             conf->curve_list = mbedtls_ecp_grp_id_list();
7312 #endif
7313 
7314 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
7315             conf->dhm_min_bitlen = 1024;
7316 #endif
7317     }
7318 
7319     return( 0 );
7320 }
7321 
7322 /*
7323  * Free mbedtls_ssl_config
7324  */
mbedtls_ssl_config_free(mbedtls_ssl_config * conf)7325 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
7326 {
7327 #if defined(MBEDTLS_DHM_C)
7328     mbedtls_mpi_free( &conf->dhm_P );
7329     mbedtls_mpi_free( &conf->dhm_G );
7330 #endif
7331 
7332 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7333     if( conf->psk != NULL )
7334     {
7335         mbedtls_zeroize( conf->psk, conf->psk_len );
7336         mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len );
7337         mbedtls_free( conf->psk );
7338         mbedtls_free( conf->psk_identity );
7339         conf->psk_len = 0;
7340         conf->psk_identity_len = 0;
7341     }
7342 #endif
7343 
7344 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7345     ssl_key_cert_free( conf->key_cert );
7346 #endif
7347 
7348     mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) );
7349 }
7350 
7351 #if defined(MBEDTLS_PK_C) && \
7352     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
7353 /*
7354  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
7355  */
mbedtls_ssl_sig_from_pk(mbedtls_pk_context * pk)7356 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
7357 {
7358 #if defined(MBEDTLS_RSA_C)
7359     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
7360         return( MBEDTLS_SSL_SIG_RSA );
7361 #endif
7362 #if defined(MBEDTLS_ECDSA_C)
7363     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
7364         return( MBEDTLS_SSL_SIG_ECDSA );
7365 #endif
7366     return( MBEDTLS_SSL_SIG_ANON );
7367 }
7368 
mbedtls_ssl_pk_alg_from_sig(unsigned char sig)7369 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
7370 {
7371     switch( sig )
7372     {
7373 #if defined(MBEDTLS_RSA_C)
7374         case MBEDTLS_SSL_SIG_RSA:
7375             return( MBEDTLS_PK_RSA );
7376 #endif
7377 #if defined(MBEDTLS_ECDSA_C)
7378         case MBEDTLS_SSL_SIG_ECDSA:
7379             return( MBEDTLS_PK_ECDSA );
7380 #endif
7381         default:
7382             return( MBEDTLS_PK_NONE );
7383     }
7384 }
7385 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
7386 
7387 /*
7388  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
7389  */
mbedtls_ssl_md_alg_from_hash(unsigned char hash)7390 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
7391 {
7392     switch( hash )
7393     {
7394 #if defined(MBEDTLS_MD5_C)
7395         case MBEDTLS_SSL_HASH_MD5:
7396             return( MBEDTLS_MD_MD5 );
7397 #endif
7398 #if defined(MBEDTLS_SHA1_C)
7399         case MBEDTLS_SSL_HASH_SHA1:
7400             return( MBEDTLS_MD_SHA1 );
7401 #endif
7402 #if defined(MBEDTLS_SHA256_C)
7403         case MBEDTLS_SSL_HASH_SHA224:
7404             return( MBEDTLS_MD_SHA224 );
7405         case MBEDTLS_SSL_HASH_SHA256:
7406             return( MBEDTLS_MD_SHA256 );
7407 #endif
7408 #if defined(MBEDTLS_SHA512_C)
7409         case MBEDTLS_SSL_HASH_SHA384:
7410             return( MBEDTLS_MD_SHA384 );
7411         case MBEDTLS_SSL_HASH_SHA512:
7412             return( MBEDTLS_MD_SHA512 );
7413 #endif
7414         default:
7415             return( MBEDTLS_MD_NONE );
7416     }
7417 }
7418 
7419 /*
7420  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
7421  */
mbedtls_ssl_hash_from_md_alg(int md)7422 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
7423 {
7424     switch( md )
7425     {
7426 #if defined(MBEDTLS_MD5_C)
7427         case MBEDTLS_MD_MD5:
7428             return( MBEDTLS_SSL_HASH_MD5 );
7429 #endif
7430 #if defined(MBEDTLS_SHA1_C)
7431         case MBEDTLS_MD_SHA1:
7432             return( MBEDTLS_SSL_HASH_SHA1 );
7433 #endif
7434 #if defined(MBEDTLS_SHA256_C)
7435         case MBEDTLS_MD_SHA224:
7436             return( MBEDTLS_SSL_HASH_SHA224 );
7437         case MBEDTLS_MD_SHA256:
7438             return( MBEDTLS_SSL_HASH_SHA256 );
7439 #endif
7440 #if defined(MBEDTLS_SHA512_C)
7441         case MBEDTLS_MD_SHA384:
7442             return( MBEDTLS_SSL_HASH_SHA384 );
7443         case MBEDTLS_MD_SHA512:
7444             return( MBEDTLS_SSL_HASH_SHA512 );
7445 #endif
7446         default:
7447             return( MBEDTLS_SSL_HASH_NONE );
7448     }
7449 }
7450 
7451 #if defined(MBEDTLS_ECP_C)
7452 /*
7453  * Check if a curve proposed by the peer is in our list.
7454  * Return 0 if we're willing to use it, -1 otherwise.
7455  */
mbedtls_ssl_check_curve(const mbedtls_ssl_context * ssl,mbedtls_ecp_group_id grp_id)7456 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
7457 {
7458     const mbedtls_ecp_group_id *gid;
7459 
7460     if( ssl->conf->curve_list == NULL )
7461         return( -1 );
7462 
7463     for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
7464         if( *gid == grp_id )
7465             return( 0 );
7466 
7467     return( -1 );
7468 }
7469 #endif /* MBEDTLS_ECP_C */
7470 
7471 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7472 /*
7473  * Check if a hash proposed by the peer is in our list.
7474  * Return 0 if we're willing to use it, -1 otherwise.
7475  */
mbedtls_ssl_check_sig_hash(const mbedtls_ssl_context * ssl,mbedtls_md_type_t md)7476 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
7477                                 mbedtls_md_type_t md )
7478 {
7479     const int *cur;
7480 
7481     if( ssl->conf->sig_hashes == NULL )
7482         return( -1 );
7483 
7484     for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
7485         if( *cur == (int) md )
7486             return( 0 );
7487 
7488     return( -1 );
7489 }
7490 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
7491 
7492 #if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_check_cert_usage(const mbedtls_x509_crt * cert,const mbedtls_ssl_ciphersuite_t * ciphersuite,int cert_endpoint,uint32_t * flags)7493 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
7494                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
7495                           int cert_endpoint,
7496                           uint32_t *flags )
7497 {
7498     int ret = 0;
7499 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7500     int usage = 0;
7501 #endif
7502 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7503     const char *ext_oid;
7504     size_t ext_len;
7505 #endif
7506 
7507 #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
7508     !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7509     ((void) cert);
7510     ((void) cert_endpoint);
7511     ((void) flags);
7512 #endif
7513 
7514 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7515     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7516     {
7517         /* Server part of the key exchange */
7518         switch( ciphersuite->key_exchange )
7519         {
7520             case MBEDTLS_KEY_EXCHANGE_RSA:
7521             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
7522                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
7523                 break;
7524 
7525             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
7526             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
7527             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
7528                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7529                 break;
7530 
7531             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
7532             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
7533                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
7534                 break;
7535 
7536             /* Don't use default: we want warnings when adding new values */
7537             case MBEDTLS_KEY_EXCHANGE_NONE:
7538             case MBEDTLS_KEY_EXCHANGE_PSK:
7539             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
7540             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
7541             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
7542                 usage = 0;
7543         }
7544     }
7545     else
7546     {
7547         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
7548         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7549     }
7550 
7551     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
7552     {
7553         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
7554         ret = -1;
7555     }
7556 #else
7557     ((void) ciphersuite);
7558 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
7559 
7560 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7561     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
7562     {
7563         ext_oid = MBEDTLS_OID_SERVER_AUTH;
7564         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
7565     }
7566     else
7567     {
7568         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
7569         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
7570     }
7571 
7572     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
7573     {
7574         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
7575         ret = -1;
7576     }
7577 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
7578 
7579     return( ret );
7580 }
7581 #endif /* MBEDTLS_X509_CRT_PARSE_C */
7582 
7583 /*
7584  * Convert version numbers to/from wire format
7585  * and, for DTLS, to/from TLS equivalent.
7586  *
7587  * For TLS this is the identity.
7588  * For DTLS, use one complement (v -> 255 - v, and then map as follows:
7589  * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)
7590  * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)
7591  */
mbedtls_ssl_write_version(int major,int minor,int transport,unsigned char ver[2])7592 void mbedtls_ssl_write_version( int major, int minor, int transport,
7593                         unsigned char ver[2] )
7594 {
7595 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7596     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7597     {
7598         if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
7599             --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
7600 
7601         ver[0] = (unsigned char)( 255 - ( major - 2 ) );
7602         ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
7603     }
7604     else
7605 #else
7606     ((void) transport);
7607 #endif
7608     {
7609         ver[0] = (unsigned char) major;
7610         ver[1] = (unsigned char) minor;
7611     }
7612 }
7613 
mbedtls_ssl_read_version(int * major,int * minor,int transport,const unsigned char ver[2])7614 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
7615                        const unsigned char ver[2] )
7616 {
7617 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7618     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7619     {
7620         *major = 255 - ver[0] + 2;
7621         *minor = 255 - ver[1] + 1;
7622 
7623         if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
7624             ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
7625     }
7626     else
7627 #else
7628     ((void) transport);
7629 #endif
7630     {
7631         *major = ver[0];
7632         *minor = ver[1];
7633     }
7634 }
7635 
mbedtls_ssl_set_calc_verify_md(mbedtls_ssl_context * ssl,int md)7636 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
7637 {
7638 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7639     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
7640         return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7641 
7642     switch( md )
7643     {
7644 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
7645 #if defined(MBEDTLS_MD5_C)
7646         case MBEDTLS_SSL_HASH_MD5:
7647             ssl->handshake->calc_verify = ssl_calc_verify_tls;
7648             break;
7649 #endif
7650 #if defined(MBEDTLS_SHA1_C)
7651         case MBEDTLS_SSL_HASH_SHA1:
7652             ssl->handshake->calc_verify = ssl_calc_verify_tls;
7653             break;
7654 #endif
7655 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
7656 #if defined(MBEDTLS_SHA512_C)
7657         case MBEDTLS_SSL_HASH_SHA384:
7658             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
7659             break;
7660 #endif
7661 #if defined(MBEDTLS_SHA256_C)
7662         case MBEDTLS_SSL_HASH_SHA256:
7663             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
7664             break;
7665 #endif
7666         default:
7667             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7668     }
7669 
7670     return 0;
7671 #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
7672     (void) ssl;
7673     (void) md;
7674 
7675     return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7676 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7677 }
7678 
7679 #endif /* MBEDTLS_SSL_TLS_C */
7680