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