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