ReactOS 0.4.16-dev-570-g1868985
ssl_tls.c
Go to the documentation of this file.
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"
75
76#include <string.h>
77
78#if defined(MBEDTLS_X509_CRT_PARSE_C)
79#include "mbedtls/oid.h"
80#endif
81
82static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl );
83static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
84
85/* Length of the "epoch" field in the record header */
86static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
87{
88#if defined(MBEDTLS_SSL_PROTO_DTLS)
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 */
101static 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 */
113static 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
127static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
129static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
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. */
138static void ssl_buffering_free( mbedtls_ssl_context *ssl );
139static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
140 uint8_t slot );
141static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
142static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
143static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
144static int ssl_buffer_message( mbedtls_ssl_context *ssl );
145static int ssl_buffer_future_record( mbedtls_ssl_context *ssl );
146static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
147
148static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl );
149static 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
157}
158
159static 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... */
170 }
171
172 return( (int) ( mtu - bytes_written ) );
173}
174
175static 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
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 */
226static 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
261static 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 */
278static unsigned int ssl_mfl_code_to_length( int mfl )
279{
280 switch( mfl )
281 {
285 return 512;
287 return 1024;
289 return 2048;
291 return 4096;
292 default:
294 }
295}
296#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
297
298#if defined(MBEDTLS_SSL_CLI_C)
299static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
300{
302 memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
303
304#if defined(MBEDTLS_X509_CRT_PARSE_C)
305 if( src->peer_cert != NULL )
306 {
307 int ret;
308
309 dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
310 if( dst->peer_cert == NULL )
312
313 mbedtls_x509_crt_init( dst->peer_cert );
314
315 if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
316 src->peer_cert->raw.len ) ) != 0 )
317 {
318 mbedtls_free( dst->peer_cert );
319 dst->peer_cert = NULL;
320 return( ret );
321 }
322 }
323#endif /* MBEDTLS_X509_CRT_PARSE_C */
324
325#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
326 if( src->ticket != NULL )
327 {
328 dst->ticket = mbedtls_calloc( 1, src->ticket_len );
329 if( dst->ticket == NULL )
331
332 memcpy( dst->ticket, src->ticket, src->ticket_len );
333 }
334#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
335
336 return( 0 );
337}
338#endif /* MBEDTLS_SSL_CLI_C */
339
340#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
341int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
342 const unsigned char *key_enc, const unsigned char *key_dec,
343 size_t keylen,
344 const unsigned char *iv_enc, const unsigned char *iv_dec,
345 size_t ivlen,
346 const unsigned char *mac_enc, const unsigned char *mac_dec,
347 size_t maclen ) = NULL;
348int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
349int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
350int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
351int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
352int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
353#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
354
355/*
356 * Key material generation
357 */
358#if defined(MBEDTLS_SSL_PROTO_SSL3)
359static int ssl3_prf( const unsigned char *secret, size_t slen,
360 const char *label,
361 const unsigned char *random, size_t rlen,
362 unsigned char *dstbuf, size_t dlen )
363{
364 int ret = 0;
365 size_t i;
368 unsigned char padding[16];
369 unsigned char sha1sum[20];
370 ((void)label);
371
374
375 /*
376 * SSLv3:
377 * block =
378 * MD5( secret + SHA1( 'A' + secret + random ) ) +
379 * MD5( secret + SHA1( 'BB' + secret + random ) ) +
380 * MD5( secret + SHA1( 'CCC' + secret + random ) ) +
381 * ...
382 */
383 for( i = 0; i < dlen / 16; i++ )
384 {
385 memset( padding, (unsigned char) ('A' + i), 1 + i );
386
387 if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
388 goto exit;
389 if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
390 goto exit;
391 if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
392 goto exit;
393 if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
394 goto exit;
395 if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
396 goto exit;
397
398 if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
399 goto exit;
400 if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
401 goto exit;
402 if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
403 goto exit;
404 if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
405 goto exit;
406 }
407
408exit:
411
413 mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
414
415 return( ret );
416}
417#endif /* MBEDTLS_SSL_PROTO_SSL3 */
418
419#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
420static int tls1_prf( const unsigned char *secret, size_t slen,
421 const char *label,
422 const unsigned char *random, size_t rlen,
423 unsigned char *dstbuf, size_t dlen )
424{
425 size_t nb, hs;
426 size_t i, j, k;
427 const unsigned char *S1, *S2;
428 unsigned char tmp[128];
429 unsigned char h_i[20];
430 const mbedtls_md_info_t *md_info;
432 int ret;
433
434 mbedtls_md_init( &md_ctx );
435
436 if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
438
439 hs = ( slen + 1 ) / 2;
440 S1 = secret;
441 S2 = secret + slen - hs;
442
443 nb = strlen( label );
444 memcpy( tmp + 20, label, nb );
445 memcpy( tmp + 20 + nb, random, rlen );
446 nb += rlen;
447
448 /*
449 * First compute P_md5(secret,label+random)[0..dlen]
450 */
451 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
453
454 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
455 return( ret );
456
457 mbedtls_md_hmac_starts( &md_ctx, S1, hs );
458 mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
459 mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
460
461 for( i = 0; i < dlen; i += 16 )
462 {
463 mbedtls_md_hmac_reset ( &md_ctx );
464 mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
465 mbedtls_md_hmac_finish( &md_ctx, h_i );
466
467 mbedtls_md_hmac_reset ( &md_ctx );
468 mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
469 mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
470
471 k = ( i + 16 > dlen ) ? dlen % 16 : 16;
472
473 for( j = 0; j < k; j++ )
474 dstbuf[i + j] = h_i[j];
475 }
476
477 mbedtls_md_free( &md_ctx );
478
479 /*
480 * XOR out with P_sha1(secret,label+random)[0..dlen]
481 */
482 if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
484
485 if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
486 return( ret );
487
488 mbedtls_md_hmac_starts( &md_ctx, S2, hs );
489 mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
490 mbedtls_md_hmac_finish( &md_ctx, tmp );
491
492 for( i = 0; i < dlen; i += 20 )
493 {
494 mbedtls_md_hmac_reset ( &md_ctx );
495 mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
496 mbedtls_md_hmac_finish( &md_ctx, h_i );
497
498 mbedtls_md_hmac_reset ( &md_ctx );
499 mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
500 mbedtls_md_hmac_finish( &md_ctx, tmp );
501
502 k = ( i + 20 > dlen ) ? dlen % 20 : 20;
503
504 for( j = 0; j < k; j++ )
505 dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
506 }
507
508 mbedtls_md_free( &md_ctx );
509
510 mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
511 mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
512
513 return( 0 );
514}
515#endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
516
517#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
518static int tls_prf_generic( mbedtls_md_type_t md_type,
519 const unsigned char *secret, size_t slen,
520 const char *label,
521 const unsigned char *random, size_t rlen,
522 unsigned char *dstbuf, size_t dlen )
523{
524 size_t nb;
525 size_t i, j, k, md_len;
526 unsigned char tmp[128];
527 unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
528 const mbedtls_md_info_t *md_info;
530 int ret;
531
532 mbedtls_md_init( &md_ctx );
533
534 if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
536
537 md_len = mbedtls_md_get_size( md_info );
538
539 if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
541
542 nb = strlen( label );
543 memcpy( tmp + md_len, label, nb );
544 memcpy( tmp + md_len + nb, random, rlen );
545 nb += rlen;
546
547 /*
548 * Compute P_<hash>(secret, label + random)[0..dlen]
549 */
550 if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
551 return( ret );
552
553 mbedtls_md_hmac_starts( &md_ctx, secret, slen );
554 mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
555 mbedtls_md_hmac_finish( &md_ctx, tmp );
556
557 for( i = 0; i < dlen; i += md_len )
558 {
559 mbedtls_md_hmac_reset ( &md_ctx );
560 mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
561 mbedtls_md_hmac_finish( &md_ctx, h_i );
562
563 mbedtls_md_hmac_reset ( &md_ctx );
564 mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
565 mbedtls_md_hmac_finish( &md_ctx, tmp );
566
567 k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
568
569 for( j = 0; j < k; j++ )
570 dstbuf[i + j] = h_i[j];
571 }
572
573 mbedtls_md_free( &md_ctx );
574
575 mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
576 mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
577
578 return( 0 );
579}
580
581#if defined(MBEDTLS_SHA256_C)
582static int tls_prf_sha256( const unsigned char *secret, size_t slen,
583 const char *label,
584 const unsigned char *random, size_t rlen,
585 unsigned char *dstbuf, size_t dlen )
586{
587 return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
588 label, random, rlen, dstbuf, dlen ) );
589}
590#endif /* MBEDTLS_SHA256_C */
591
592#if defined(MBEDTLS_SHA512_C)
593static int tls_prf_sha384( const unsigned char *secret, size_t slen,
594 const char *label,
595 const unsigned char *random, size_t rlen,
596 unsigned char *dstbuf, size_t dlen )
597{
598 return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
599 label, random, rlen, dstbuf, dlen ) );
600}
601#endif /* MBEDTLS_SHA512_C */
602#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
603
604static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
605
606#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
607 defined(MBEDTLS_SSL_PROTO_TLS1_1)
608static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
609#endif
610
611#if defined(MBEDTLS_SSL_PROTO_SSL3)
612static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
613static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
614#endif
615
616#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
617static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
618static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
619#endif
620
621#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
622#if defined(MBEDTLS_SHA256_C)
623static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
624static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *, unsigned char * );
625static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
626#endif
627
628#if defined(MBEDTLS_SHA512_C)
629static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
630static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
631static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
632#endif
633#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
634
636{
637 int ret = 0;
638 unsigned char tmp[64];
639 unsigned char keyblk[256];
640 unsigned char *key1;
641 unsigned char *key2;
642 unsigned char *mac_enc;
643 unsigned char *mac_dec;
644 size_t mac_key_len;
645 size_t iv_copy_len;
646 const mbedtls_cipher_info_t *cipher_info;
647 const mbedtls_md_info_t *md_info;
648
651 mbedtls_ssl_handshake_params *handshake = ssl->handshake;
652
653 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
654
655 cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
656 if( cipher_info == NULL )
657 {
658 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
659 transform->ciphersuite_info->cipher ) );
661 }
662
663 md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
664 if( md_info == NULL )
665 {
666 MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
667 transform->ciphersuite_info->mac ) );
669 }
670
671 /*
672 * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
673 */
674#if defined(MBEDTLS_SSL_PROTO_SSL3)
676 {
677 handshake->tls_prf = ssl3_prf;
678 handshake->calc_verify = ssl_calc_verify_ssl;
679 handshake->calc_finished = ssl_calc_finished_ssl;
680 }
681 else
682#endif
683#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
685 {
686 handshake->tls_prf = tls1_prf;
687 handshake->calc_verify = ssl_calc_verify_tls;
688 handshake->calc_finished = ssl_calc_finished_tls;
689 }
690 else
691#endif
692#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
693#if defined(MBEDTLS_SHA512_C)
695 transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
696 {
697 handshake->tls_prf = tls_prf_sha384;
698 handshake->calc_verify = ssl_calc_verify_tls_sha384;
699 handshake->calc_finished = ssl_calc_finished_tls_sha384;
700 }
701 else
702#endif
703#if defined(MBEDTLS_SHA256_C)
705 {
706 handshake->tls_prf = tls_prf_sha256;
707 handshake->calc_verify = ssl_calc_verify_tls_sha256;
708 handshake->calc_finished = ssl_calc_finished_tls_sha256;
709 }
710 else
711#endif
712#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
713 {
714 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
716 }
717
718 /*
719 * SSLv3:
720 * master =
721 * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) +
722 * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) +
723 * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
724 *
725 * TLSv1+:
726 * master = PRF( premaster, "master secret", randbytes )[0..47]
727 */
728 if( handshake->resume == 0 )
729 {
730 MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
731 handshake->pmslen );
732
733#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
735 {
736 unsigned char session_hash[48];
737 size_t hash_len;
738
739 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
740
741 ssl->handshake->calc_verify( ssl, session_hash );
742
743#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
745 {
746#if defined(MBEDTLS_SHA512_C)
749 {
750 hash_len = 48;
751 }
752 else
753#endif
754 hash_len = 32;
755 }
756 else
757#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
758 hash_len = 36;
759
760 MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
761
762 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
763 "extended master secret",
764 session_hash, hash_len,
765 session->master, 48 );
766 if( ret != 0 )
767 {
768 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
769 return( ret );
770 }
771
772 }
773 else
774#endif
775 ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
776 "master secret",
777 handshake->randbytes, 64,
778 session->master, 48 );
779 if( ret != 0 )
780 {
781 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
782 return( ret );
783 }
784
786 sizeof(handshake->premaster) );
787 }
788 else
789 MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
790
791 /*
792 * Swap the client and server random values.
793 */
794 memcpy( tmp, handshake->randbytes, 64 );
795 memcpy( handshake->randbytes, tmp + 32, 32 );
796 memcpy( handshake->randbytes + 32, tmp, 32 );
797 mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
798
799 /*
800 * SSLv3:
801 * key block =
802 * MD5( master + SHA1( 'A' + master + randbytes ) ) +
803 * MD5( master + SHA1( 'BB' + master + randbytes ) ) +
804 * MD5( master + SHA1( 'CCC' + master + randbytes ) ) +
805 * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
806 * ...
807 *
808 * TLSv1:
809 * key block = PRF( master, "key expansion", randbytes )
810 */
811 ret = handshake->tls_prf( session->master, 48, "key expansion",
812 handshake->randbytes, 64, keyblk, 256 );
813 if( ret != 0 )
814 {
815 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
816 return( ret );
817 }
818
819 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
820 mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
821 MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
822 MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
823 MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
824
826 sizeof( handshake->randbytes ) );
827
828 /*
829 * Determine the appropriate key, IV and MAC length.
830 */
831
832 transform->keylen = cipher_info->key_bitlen / 8;
833
834 if( cipher_info->mode == MBEDTLS_MODE_GCM ||
835 cipher_info->mode == MBEDTLS_MODE_CCM ||
836 cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
837 {
838 size_t taglen, explicit_ivlen;
839
840 transform->maclen = 0;
841 mac_key_len = 0;
842
843 /* All modes haves 96-bit IVs;
844 * GCM and CCM has 4 implicit and 8 explicit bytes
845 * ChachaPoly has all 12 bytes implicit
846 */
847 transform->ivlen = 12;
848 if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
849 transform->fixed_ivlen = 12;
850 else
851 transform->fixed_ivlen = 4;
852
853 /* All modes have 128-bit tags, except CCM_8 (ciphersuite flag) */
854 taglen = transform->ciphersuite_info->flags &
856
857
858 /* Minimum length of encrypted record */
859 explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
860 transform->minlen = explicit_ivlen + taglen;
861 }
862 else
863 {
864 /* Initialize HMAC contexts */
865 if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
866 ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
867 {
868 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
869 return( ret );
870 }
871
872 /* Get MAC length */
873 mac_key_len = mbedtls_md_get_size( md_info );
874 transform->maclen = mac_key_len;
875
876#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
877 /*
878 * If HMAC is to be truncated, we shall keep the leftmost bytes,
879 * (rfc 6066 page 13 or rfc 2104 section 4),
880 * so we only need to adjust the length here.
881 */
882 if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
883 {
885
886#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
887 /* Fall back to old, non-compliant version of the truncated
888 * HMAC implementation which also truncates the key
889 * (Mbed TLS versions from 1.3 to 2.6.0) */
890 mac_key_len = transform->maclen;
891#endif
892 }
893#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
894
895 /* IV length */
896 transform->ivlen = cipher_info->iv_size;
897
898 /* Minimum length */
899 if( cipher_info->mode == MBEDTLS_MODE_STREAM )
900 transform->minlen = transform->maclen;
901 else
902 {
903 /*
904 * GenericBlockCipher:
905 * 1. if EtM is in use: one block plus MAC
906 * otherwise: * first multiple of blocklen greater than maclen
907 * 2. IV except for SSL3 and TLS 1.0
908 */
909#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
910 if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
911 {
912 transform->minlen = transform->maclen
913 + cipher_info->block_size;
914 }
915 else
916#endif
917 {
918 transform->minlen = transform->maclen
919 + cipher_info->block_size
920 - transform->maclen % cipher_info->block_size;
921 }
922
923#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
926 ; /* No need to adjust minlen */
927 else
928#endif
929#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
932 {
933 transform->minlen += transform->ivlen;
934 }
935 else
936#endif
937 {
938 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
940 }
941 }
942 }
943
944 MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
945 transform->keylen, transform->minlen, transform->ivlen,
946 transform->maclen ) );
947
948 /*
949 * Finally setup the cipher contexts, IVs and MAC secrets.
950 */
951#if defined(MBEDTLS_SSL_CLI_C)
952 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
953 {
954 key1 = keyblk + mac_key_len * 2;
955 key2 = keyblk + mac_key_len * 2 + transform->keylen;
956
957 mac_enc = keyblk;
958 mac_dec = keyblk + mac_key_len;
959
960 /*
961 * This is not used in TLS v1.1.
962 */
963 iv_copy_len = ( transform->fixed_ivlen ) ?
964 transform->fixed_ivlen : transform->ivlen;
965 memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len );
966 memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
967 iv_copy_len );
968 }
969 else
970#endif /* MBEDTLS_SSL_CLI_C */
971#if defined(MBEDTLS_SSL_SRV_C)
972 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
973 {
974 key1 = keyblk + mac_key_len * 2 + transform->keylen;
975 key2 = keyblk + mac_key_len * 2;
976
977 mac_enc = keyblk + mac_key_len;
978 mac_dec = keyblk;
979
980 /*
981 * This is not used in TLS v1.1.
982 */
983 iv_copy_len = ( transform->fixed_ivlen ) ?
984 transform->fixed_ivlen : transform->ivlen;
985 memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len );
986 memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
987 iv_copy_len );
988 }
989 else
990#endif /* MBEDTLS_SSL_SRV_C */
991 {
992 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
994 }
995
996#if defined(MBEDTLS_SSL_PROTO_SSL3)
998 {
999 if( mac_key_len > sizeof transform->mac_enc )
1000 {
1001 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1003 }
1004
1005 memcpy( transform->mac_enc, mac_enc, mac_key_len );
1006 memcpy( transform->mac_dec, mac_dec, mac_key_len );
1007 }
1008 else
1009#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1010#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1011 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1013 {
1014 /* For HMAC-based ciphersuites, initialize the HMAC transforms.
1015 For AEAD-based ciphersuites, there is nothing to do here. */
1016 if( mac_key_len != 0 )
1017 {
1018 mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
1019 mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
1020 }
1021 }
1022 else
1023#endif
1024 {
1025 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1027 }
1028
1029#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
1030 if( mbedtls_ssl_hw_record_init != NULL )
1031 {
1032 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
1033
1034 if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
1035 transform->iv_enc, transform->iv_dec,
1036 iv_copy_len,
1037 mac_enc, mac_dec,
1038 mac_key_len ) ) != 0 )
1039 {
1040 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
1042 }
1043 }
1044#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
1045
1046#if defined(MBEDTLS_SSL_EXPORT_KEYS)
1047 if( ssl->conf->f_export_keys != NULL )
1048 {
1049 ssl->conf->f_export_keys( ssl->conf->p_export_keys,
1050 session->master, keyblk,
1051 mac_key_len, transform->keylen,
1052 iv_copy_len );
1053 }
1054#endif
1055
1056 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
1057 cipher_info ) ) != 0 )
1058 {
1059 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
1060 return( ret );
1061 }
1062
1063 if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
1064 cipher_info ) ) != 0 )
1065 {
1066 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
1067 return( ret );
1068 }
1069
1070 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
1071 cipher_info->key_bitlen,
1072 MBEDTLS_ENCRYPT ) ) != 0 )
1073 {
1074 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
1075 return( ret );
1076 }
1077
1078 if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
1079 cipher_info->key_bitlen,
1080 MBEDTLS_DECRYPT ) ) != 0 )
1081 {
1082 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
1083 return( ret );
1084 }
1085
1086#if defined(MBEDTLS_CIPHER_MODE_CBC)
1087 if( cipher_info->mode == MBEDTLS_MODE_CBC )
1088 {
1089 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
1090 MBEDTLS_PADDING_NONE ) ) != 0 )
1091 {
1092 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
1093 return( ret );
1094 }
1095
1096 if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
1097 MBEDTLS_PADDING_NONE ) ) != 0 )
1098 {
1099 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
1100 return( ret );
1101 }
1102 }
1103#endif /* MBEDTLS_CIPHER_MODE_CBC */
1104
1105 mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
1106
1107#if defined(MBEDTLS_ZLIB_SUPPORT)
1108 // Initialize compression
1109 //
1110 if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
1111 {
1112 if( ssl->compress_buf == NULL )
1113 {
1114 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
1115 ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
1116 if( ssl->compress_buf == NULL )
1117 {
1118 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
1119 MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
1121 }
1122 }
1123
1124 MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
1125
1126 memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
1127 memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
1128
1129 if( deflateInit( &transform->ctx_deflate,
1131 inflateInit( &transform->ctx_inflate ) != Z_OK )
1132 {
1133 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
1135 }
1136 }
1137#endif /* MBEDTLS_ZLIB_SUPPORT */
1138
1139 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
1140
1141 return( 0 );
1142}
1143
1144#if defined(MBEDTLS_SSL_PROTO_SSL3)
1145void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char *hash )
1146{
1149 unsigned char pad_1[48];
1150 unsigned char pad_2[48];
1151
1152 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
1153
1156
1159
1160 memset( pad_1, 0x36, 48 );
1161 memset( pad_2, 0x5C, 48 );
1162
1164 mbedtls_md5_update_ret( &md5, pad_1, 48 );
1166
1169 mbedtls_md5_update_ret( &md5, pad_2, 48 );
1172
1174 mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
1176
1179 mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
1180 mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
1182
1183 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1184 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1185
1188
1189 return;
1190}
1191#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1192
1193#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1194void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char *hash )
1195{
1198
1199 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
1200
1203
1206
1209
1210 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
1211 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1212
1215
1216 return;
1217}
1218#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1219
1220#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1221#if defined(MBEDTLS_SHA256_C)
1222void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char *hash )
1223{
1225
1227
1228 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
1229
1232
1233 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
1234 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1235
1237
1238 return;
1239}
1240#endif /* MBEDTLS_SHA256_C */
1241
1242#if defined(MBEDTLS_SHA512_C)
1243void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char *hash )
1244{
1246
1248
1249 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
1250
1253
1254 MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
1255 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
1256
1258
1259 return;
1260}
1261#endif /* MBEDTLS_SHA512_C */
1262#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1263
1264#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
1265int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
1266{
1267 unsigned char *p = ssl->handshake->premaster;
1268 unsigned char *end = p + sizeof( ssl->handshake->premaster );
1269 const unsigned char *psk = ssl->conf->psk;
1270 size_t psk_len = ssl->conf->psk_len;
1271
1272 /* If the psk callback was called, use its result */
1273 if( ssl->handshake->psk != NULL )
1274 {
1275 psk = ssl->handshake->psk;
1276 psk_len = ssl->handshake->psk_len;
1277 }
1278
1279 /*
1280 * PMS = struct {
1281 * opaque other_secret<0..2^16-1>;
1282 * opaque psk<0..2^16-1>;
1283 * };
1284 * with "other_secret" depending on the particular key exchange
1285 */
1286#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1287 if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
1288 {
1289 if( end - p < 2 )
1291
1292 *(p++) = (unsigned char)( psk_len >> 8 );
1293 *(p++) = (unsigned char)( psk_len );
1294
1295 if( end < p || (size_t)( end - p ) < psk_len )
1297
1298 memset( p, 0, psk_len );
1299 p += psk_len;
1300 }
1301 else
1302#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1303#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1304 if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
1305 {
1306 /*
1307 * other_secret already set by the ClientKeyExchange message,
1308 * and is 48 bytes long
1309 */
1310 if( end - p < 2 )
1312
1313 *p++ = 0;
1314 *p++ = 48;
1315 p += 48;
1316 }
1317 else
1318#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1319#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1320 if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
1321 {
1322 int ret;
1323 size_t len;
1324
1325 /* Write length only when we know the actual value */
1327 p + 2, end - ( p + 2 ), &len,
1328 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1329 {
1330 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
1331 return( ret );
1332 }
1333 *(p++) = (unsigned char)( len >> 8 );
1334 *(p++) = (unsigned char)( len );
1335 p += len;
1336
1337 MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
1338 }
1339 else
1340#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1341#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
1342 if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
1343 {
1344 int ret;
1345 size_t zlen;
1346
1347 if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
1348 p + 2, end - ( p + 2 ),
1349 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
1350 {
1351 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
1352 return( ret );
1353 }
1354
1355 *(p++) = (unsigned char)( zlen >> 8 );
1356 *(p++) = (unsigned char)( zlen );
1357 p += zlen;
1358
1361 }
1362 else
1363#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
1364 {
1365 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1367 }
1368
1369 /* opaque psk<0..2^16-1>; */
1370 if( end - p < 2 )
1372
1373 *(p++) = (unsigned char)( psk_len >> 8 );
1374 *(p++) = (unsigned char)( psk_len );
1375
1376 if( end < p || (size_t)( end - p ) < psk_len )
1378
1379 memcpy( p, psk, psk_len );
1380 p += psk_len;
1381
1382 ssl->handshake->pmslen = p - ssl->handshake->premaster;
1383
1384 return( 0 );
1385}
1386#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
1387
1388#if defined(MBEDTLS_SSL_PROTO_SSL3)
1389/*
1390 * SSLv3.0 MAC functions
1391 */
1392#define SSL_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */
1393static void ssl_mac( mbedtls_md_context_t *md_ctx,
1394 const unsigned char *secret,
1395 const unsigned char *buf, size_t len,
1396 const unsigned char *ctr, int type,
1397 unsigned char out[SSL_MAC_MAX_BYTES] )
1398{
1399 unsigned char header[11];
1400 unsigned char padding[48];
1401 int padlen;
1402 int md_size = mbedtls_md_get_size( md_ctx->md_info );
1403 int md_type = mbedtls_md_get_type( md_ctx->md_info );
1404
1405 /* Only MD5 and SHA-1 supported */
1406 if( md_type == MBEDTLS_MD_MD5 )
1407 padlen = 48;
1408 else
1409 padlen = 40;
1410
1411 memcpy( header, ctr, 8 );
1412 header[ 8] = (unsigned char) type;
1413 header[ 9] = (unsigned char)( len >> 8 );
1414 header[10] = (unsigned char)( len );
1415
1416 memset( padding, 0x36, padlen );
1417 mbedtls_md_starts( md_ctx );
1418 mbedtls_md_update( md_ctx, secret, md_size );
1419 mbedtls_md_update( md_ctx, padding, padlen );
1420 mbedtls_md_update( md_ctx, header, 11 );
1421 mbedtls_md_update( md_ctx, buf, len );
1422 mbedtls_md_finish( md_ctx, out );
1423
1424 memset( padding, 0x5C, padlen );
1425 mbedtls_md_starts( md_ctx );
1426 mbedtls_md_update( md_ctx, secret, md_size );
1427 mbedtls_md_update( md_ctx, padding, padlen );
1428 mbedtls_md_update( md_ctx, out, md_size );
1429 mbedtls_md_finish( md_ctx, out );
1430}
1431#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1432
1433#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
1434 defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1435#define SSL_SOME_MODES_USE_MAC
1436#endif
1437
1438/*
1439 * Encryption/decryption functions
1440 */
1441static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
1442{
1444 int auth_done = 0;
1445
1446 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
1447
1448 if( ssl->session_out == NULL || ssl->transform_out == NULL )
1449 {
1450 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1452 }
1453
1455
1456 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
1457 ssl->out_msg, ssl->out_msglen );
1458
1459 /*
1460 * Add MAC before if needed
1461 */
1462#if defined(SSL_SOME_MODES_USE_MAC)
1463 if( mode == MBEDTLS_MODE_STREAM ||
1467#endif
1468 ) )
1469 {
1470#if defined(MBEDTLS_SSL_PROTO_SSL3)
1472 {
1473 unsigned char mac[SSL_MAC_MAX_BYTES];
1474
1475 ssl_mac( &ssl->transform_out->md_ctx_enc,
1476 ssl->transform_out->mac_enc,
1477 ssl->out_msg, ssl->out_msglen,
1478 ssl->out_ctr, ssl->out_msgtype,
1479 mac );
1480
1481 memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
1482 }
1483 else
1484#endif
1485#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1486 defined(MBEDTLS_SSL_PROTO_TLS1_2)
1488 {
1489 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1490
1495 ssl->out_msg, ssl->out_msglen );
1498
1499 memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
1500 }
1501 else
1502#endif
1503 {
1504 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1506 }
1507
1508 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
1509 ssl->out_msg + ssl->out_msglen,
1510 ssl->transform_out->maclen );
1511
1512 ssl->out_msglen += ssl->transform_out->maclen;
1513 auth_done++;
1514 }
1515#endif /* AEAD not the only option */
1516
1517 /*
1518 * Encrypt
1519 */
1520#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1521 if( mode == MBEDTLS_MODE_STREAM )
1522 {
1523 int ret;
1524 size_t olen = 0;
1525
1526 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1527 "including %d bytes of padding",
1528 ssl->out_msglen, 0 ) );
1529
1531 ssl->transform_out->iv_enc,
1532 ssl->transform_out->ivlen,
1533 ssl->out_msg, ssl->out_msglen,
1534 ssl->out_msg, &olen ) ) != 0 )
1535 {
1536 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1537 return( ret );
1538 }
1539
1540 if( ssl->out_msglen != olen )
1541 {
1542 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1544 }
1545 }
1546 else
1547#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1548#if defined(MBEDTLS_GCM_C) || \
1549 defined(MBEDTLS_CCM_C) || \
1550 defined(MBEDTLS_CHACHAPOLY_C)
1551 if( mode == MBEDTLS_MODE_GCM ||
1554 {
1555 int ret;
1556 size_t enc_msglen, olen;
1557 unsigned char *enc_msg;
1558 unsigned char add_data[13];
1559 unsigned char iv[12];
1561 unsigned char taglen = transform->ciphersuite_info->flags &
1563 size_t explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
1564
1565 /*
1566 * Prepare additional authenticated data
1567 */
1568 memcpy( add_data, ssl->out_ctr, 8 );
1569 add_data[8] = ssl->out_msgtype;
1571 ssl->conf->transport, add_data + 9 );
1572 add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
1573 add_data[12] = ssl->out_msglen & 0xFF;
1574
1575 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
1576
1577 /*
1578 * Generate IV
1579 */
1580 if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
1581 {
1582 /* GCM and CCM: fixed || explicit (=seqnum) */
1583 memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
1584 memcpy( iv + transform->fixed_ivlen, ssl->out_ctr, 8 );
1585 memcpy( ssl->out_iv, ssl->out_ctr, 8 );
1586
1587 }
1588 else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
1589 {
1590 /* ChachaPoly: fixed XOR sequence number */
1591 unsigned char i;
1592
1593 memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
1594
1595 for( i = 0; i < 8; i++ )
1596 iv[i+4] ^= ssl->out_ctr[i];
1597 }
1598 else
1599 {
1600 /* Reminder if we ever add an AEAD mode with a different size */
1601 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1603 }
1604
1605 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
1606 iv, transform->ivlen );
1607 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
1608 ssl->out_iv, explicit_ivlen );
1609
1610 /*
1611 * Fix message length with added IV
1612 */
1613 enc_msg = ssl->out_msg;
1614 enc_msglen = ssl->out_msglen;
1615 ssl->out_msglen += explicit_ivlen;
1616
1617 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1618 "including 0 bytes of padding",
1619 ssl->out_msglen ) );
1620
1621 /*
1622 * Encrypt and authenticate
1623 */
1624 if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
1625 iv, transform->ivlen,
1626 add_data, 13,
1627 enc_msg, enc_msglen,
1628 enc_msg, &olen,
1629 enc_msg + enc_msglen, taglen ) ) != 0 )
1630 {
1631 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
1632 return( ret );
1633 }
1634
1635 if( olen != enc_msglen )
1636 {
1637 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1639 }
1640
1641 ssl->out_msglen += taglen;
1642 auth_done++;
1643
1644 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
1645 }
1646 else
1647#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
1648#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
1649 if( mode == MBEDTLS_MODE_CBC )
1650 {
1651 int ret;
1652 unsigned char *enc_msg;
1653 size_t enc_msglen, padlen, olen = 0, i;
1654
1655 padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
1656 ssl->transform_out->ivlen;
1657 if( padlen == ssl->transform_out->ivlen )
1658 padlen = 0;
1659
1660 for( i = 0; i <= padlen; i++ )
1661 ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
1662
1663 ssl->out_msglen += padlen + 1;
1664
1665 enc_msglen = ssl->out_msglen;
1666 enc_msg = ssl->out_msg;
1667
1668#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1669 /*
1670 * Prepend per-record IV for block cipher in TLS v1.1 and up as per
1671 * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
1672 */
1674 {
1675 /*
1676 * Generate IV
1677 */
1678 ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
1679 ssl->transform_out->ivlen );
1680 if( ret != 0 )
1681 return( ret );
1682
1683 memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
1684 ssl->transform_out->ivlen );
1685
1686 /*
1687 * Fix pointer positions and message length with added IV
1688 */
1689 enc_msg = ssl->out_msg;
1690 enc_msglen = ssl->out_msglen;
1691 ssl->out_msglen += ssl->transform_out->ivlen;
1692 }
1693#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
1694
1695 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
1696 "including %d bytes of IV and %d bytes of padding",
1697 ssl->out_msglen, ssl->transform_out->ivlen,
1698 padlen + 1 ) );
1699
1701 ssl->transform_out->iv_enc,
1702 ssl->transform_out->ivlen,
1703 enc_msg, enc_msglen,
1704 enc_msg, &olen ) ) != 0 )
1705 {
1706 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1707 return( ret );
1708 }
1709
1710 if( enc_msglen != olen )
1711 {
1712 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1714 }
1715
1716#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1718 {
1719 /*
1720 * Save IV in SSL3 and TLS1
1721 */
1724 ssl->transform_out->ivlen );
1725 }
1726#endif
1727
1728#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1729 if( auth_done == 0 )
1730 {
1731 unsigned char mac[MBEDTLS_SSL_MAC_ADD];
1732
1733 /*
1734 * MAC(MAC_write_key, seq_num +
1735 * TLSCipherText.type +
1736 * TLSCipherText.version +
1737 * length_of( (IV +) ENC(...) ) +
1738 * IV + // except for TLS 1.0
1739 * ENC(content + padding + padding_length));
1740 */
1741 unsigned char pseudo_hdr[13];
1742
1743 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
1744
1745 memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 );
1746 memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 );
1747 pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
1748 pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF );
1749
1750 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
1751
1752 mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
1754 ssl->out_iv, ssl->out_msglen );
1757
1758 memcpy( ssl->out_iv + ssl->out_msglen, mac,
1759 ssl->transform_out->maclen );
1760
1761 ssl->out_msglen += ssl->transform_out->maclen;
1762 auth_done++;
1763 }
1764#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1765 }
1766 else
1767#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */
1768 {
1769 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1771 }
1772
1773 /* Make extra sure authentication was performed, exactly once */
1774 if( auth_done != 1 )
1775 {
1776 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1778 }
1779
1780 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
1781
1782 return( 0 );
1783}
1784
1785#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
1786/*
1787 * Constant-flow conditional memcpy:
1788 * - if c1 == c2, equivalent to memcpy(dst, src, len),
1789 * - otherwise, a no-op,
1790 * but with execution flow independent of the values of c1 and c2.
1791 *
1792 * Use only bit operations to avoid branches that could be used by some
1793 * compilers on some platforms to translate comparison operators.
1794 */
1795static void mbedtls_ssl_cf_memcpy_if_eq( unsigned char *dst,
1796 const unsigned char *src,
1797 size_t len,
1798 size_t c1, size_t c2 )
1799{
1800 /* diff = 0 if c1 == c2, non-zero otherwise */
1801 const size_t diff = c1 ^ c2;
1802
1803 /* MSVC has a warning about unary minus on unsigned integer types,
1804 * but this is well-defined and precisely what we want to do here. */
1805#if defined(_MSC_VER)
1806#pragma warning( push )
1807#pragma warning( disable : 4146 )
1808#endif
1809
1810 /* diff_msb's most significant bit is equal to c1 != c2 */
1811 const size_t diff_msb = ( diff | -diff );
1812
1813 /* diff1 = c1 != c2 */
1814 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
1815
1816 /* mask = c1 != c2 ? 0xff : 0x00 */
1817 const unsigned char mask = (unsigned char) -diff1;
1818
1819#if defined(_MSC_VER)
1820#pragma warning( pop )
1821#endif
1822
1823 /* dst[i] = c1 != c2 ? dst[i] : src[i] */
1824 size_t i;
1825 for( i = 0; i < len; i++ )
1826 dst[i] = ( dst[i] & mask ) | ( src[i] & ~mask );
1827}
1828
1829/*
1830 * Compute HMAC of variable-length data with constant flow.
1831 *
1832 * Only works with MD-5, SHA-1, SHA-256 and SHA-384.
1833 * (Otherwise, computation of block_size needs to be adapted.)
1834 */
1837 const unsigned char *add_data, size_t add_data_len,
1838 const unsigned char *data, size_t data_len_secret,
1839 size_t min_data_len, size_t max_data_len,
1840 unsigned char *output )
1841{
1842 /*
1843 * This function breaks the HMAC abstraction and uses the md_clone()
1844 * extension to the MD API in order to get constant-flow behaviour.
1845 *
1846 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
1847 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
1848 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
1849 *
1850 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
1851 * minlen, then cloning the context, and for each byte up to maxlen
1852 * finishing up the hash computation, keeping only the correct result.
1853 *
1854 * Then we only need to compute HASH(okey + inner_hash) and we're done.
1855 */
1856 const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
1857 /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
1858 * all of which have the same block size except SHA-384. */
1859 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
1860 const unsigned char * const ikey = ctx->hmac_ctx;
1861 const unsigned char * const okey = ikey + block_size;
1862 const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
1863
1864 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
1866 size_t offset;
1867 int ret;
1868
1869 mbedtls_md_init( &aux );
1870
1871#define MD_CHK( func_call ) \
1872 do { \
1873 ret = (func_call); \
1874 if( ret != 0 ) \
1875 goto cleanup; \
1876 } while( 0 )
1877
1878 MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
1879
1880 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
1881 * so we can start directly with the message */
1882 MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
1883 MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
1884
1885 /* For each possible length, compute the hash up to that point */
1886 for( offset = min_data_len; offset <= max_data_len; offset++ )
1887 {
1888 MD_CHK( mbedtls_md_clone( &aux, ctx ) );
1889 MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
1890 /* Keep only the correct inner_hash in the output buffer */
1891 mbedtls_ssl_cf_memcpy_if_eq( output, aux_out, hash_size,
1892 offset, data_len_secret );
1893
1894 if( offset < max_data_len )
1895 MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
1896 }
1897
1898 /* The context needs to finish() before it starts() again */
1899 MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
1900
1901 /* Now compute HASH(okey + inner_hash) */
1902 MD_CHK( mbedtls_md_starts( ctx ) );
1903 MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
1904 MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
1905 MD_CHK( mbedtls_md_finish( ctx, output ) );
1906
1907 /* Done, get ready for next time */
1908 MD_CHK( mbedtls_md_hmac_reset( ctx ) );
1909
1910#undef MD_CHK
1911
1912cleanup:
1913 mbedtls_md_free( &aux );
1914 return( ret );
1915}
1916
1917/*
1918 * Constant-flow memcpy from variable position in buffer.
1919 * - functionally equivalent to memcpy(dst, src + offset_secret, len)
1920 * - but with execution flow independent from the value of offset_secret.
1921 */
1922void mbedtls_ssl_cf_memcpy_offset( unsigned char *dst,
1923 const unsigned char *src_base,
1924 size_t offset_secret,
1925 size_t offset_min, size_t offset_max,
1926 size_t len )
1927{
1928 size_t offset;
1929
1930 for( offset = offset_min; offset <= offset_max; offset++ )
1931 {
1932 mbedtls_ssl_cf_memcpy_if_eq( dst, src_base + offset, len,
1933 offset, offset_secret );
1934 }
1935}
1936#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
1937
1938static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
1939{
1941 int auth_done = 0;
1942#if defined(SSL_SOME_MODES_USE_MAC)
1943 size_t padlen = 0, correct = 1;
1944#endif
1945
1946 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
1947
1948 if( ssl->session_in == NULL || ssl->transform_in == NULL )
1949 {
1950 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1952 }
1953
1955
1956 if( ssl->in_msglen < ssl->transform_in->minlen )
1957 {
1958 MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
1959 ssl->in_msglen, ssl->transform_in->minlen ) );
1961 }
1962
1963#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
1964 if( mode == MBEDTLS_MODE_STREAM )
1965 {
1966 int ret;
1967 size_t olen = 0;
1968
1969 padlen = 0;
1970
1972 ssl->transform_in->iv_dec,
1973 ssl->transform_in->ivlen,
1974 ssl->in_msg, ssl->in_msglen,
1975 ssl->in_msg, &olen ) ) != 0 )
1976 {
1977 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
1978 return( ret );
1979 }
1980
1981 if( ssl->in_msglen != olen )
1982 {
1983 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1985 }
1986 }
1987 else
1988#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
1989#if defined(MBEDTLS_GCM_C) || \
1990 defined(MBEDTLS_CCM_C) || \
1991 defined(MBEDTLS_CHACHAPOLY_C)
1992 if( mode == MBEDTLS_MODE_GCM ||
1995 {
1996 int ret;
1997 size_t dec_msglen, olen;
1998 unsigned char *dec_msg;
1999 unsigned char *dec_msg_result;
2000 unsigned char add_data[13];
2001 unsigned char iv[12];
2003 unsigned char taglen = transform->ciphersuite_info->flags &
2005 size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
2006
2007 /*
2008 * Compute and update sizes
2009 */
2010 if( ssl->in_msglen < explicit_iv_len + taglen )
2011 {
2012 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
2013 "+ taglen (%d)", ssl->in_msglen,
2014 explicit_iv_len, taglen ) );
2016 }
2017 dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
2018
2019 dec_msg = ssl->in_msg;
2020 dec_msg_result = ssl->in_msg;
2021 ssl->in_msglen = dec_msglen;
2022
2023 /*
2024 * Prepare additional authenticated data
2025 */
2026 memcpy( add_data, ssl->in_ctr, 8 );
2027 add_data[8] = ssl->in_msgtype;
2029 ssl->conf->transport, add_data + 9 );
2030 add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
2031 add_data[12] = ssl->in_msglen & 0xFF;
2032
2033 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
2034
2035 /*
2036 * Prepare IV
2037 */
2038 if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
2039 {
2040 /* GCM and CCM: fixed || explicit (transmitted) */
2041 memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
2042 memcpy( iv + transform->fixed_ivlen, ssl->in_iv, 8 );
2043
2044 }
2045 else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
2046 {
2047 /* ChachaPoly: fixed XOR sequence number */
2048 unsigned char i;
2049
2050 memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
2051
2052 for( i = 0; i < 8; i++ )
2053 iv[i+4] ^= ssl->in_ctr[i];
2054 }
2055 else
2056 {
2057 /* Reminder if we ever add an AEAD mode with a different size */
2058 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2060 }
2061
2062 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
2063 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
2064
2065 /*
2066 * Decrypt and authenticate
2067 */
2069 iv, transform->ivlen,
2070 add_data, 13,
2071 dec_msg, dec_msglen,
2072 dec_msg_result, &olen,
2073 dec_msg + dec_msglen, taglen ) ) != 0 )
2074 {
2075 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
2076
2079
2080 return( ret );
2081 }
2082 auth_done++;
2083
2084 if( olen != dec_msglen )
2085 {
2086 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2088 }
2089 }
2090 else
2091#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
2092#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
2093 if( mode == MBEDTLS_MODE_CBC )
2094 {
2095 /*
2096 * Decrypt and check the padding
2097 */
2098 int ret;
2099 unsigned char *dec_msg;
2100 unsigned char *dec_msg_result;
2101 size_t dec_msglen;
2102 size_t minlen = 0;
2103 size_t olen = 0;
2104
2105 /*
2106 * Check immediate ciphertext sanity
2107 */
2108#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
2110 minlen += ssl->transform_in->ivlen;
2111#endif
2112
2113 if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
2114 ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
2115 {
2116 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
2117 "+ 1 ) ( + expl IV )", ssl->in_msglen,
2118 ssl->transform_in->ivlen,
2119 ssl->transform_in->maclen ) );
2121 }
2122
2123 dec_msglen = ssl->in_msglen;
2124 dec_msg = ssl->in_msg;
2125 dec_msg_result = ssl->in_msg;
2126
2127 /*
2128 * Authenticate before decrypt if enabled
2129 */
2130#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2132 {
2133 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
2134 unsigned char pseudo_hdr[13];
2135
2136 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
2137
2138 dec_msglen -= ssl->transform_in->maclen;
2139 ssl->in_msglen -= ssl->transform_in->maclen;
2140
2141 memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 );
2142 memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 );
2143 pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
2144 pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF );
2145
2146 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
2147
2148 mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
2150 ssl->in_iv, ssl->in_msglen );
2151 mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
2153
2154 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen,
2155 ssl->transform_in->maclen );
2156 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
2157 ssl->transform_in->maclen );
2158
2159 if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,
2160 ssl->transform_in->maclen ) != 0 )
2161 {
2162 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
2163
2165 }
2166 auth_done++;
2167 }
2168#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
2169
2170 /*
2171 * Check length sanity
2172 */
2173 if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
2174 {
2175 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
2176 ssl->in_msglen, ssl->transform_in->ivlen ) );
2178 }
2179
2180#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
2181 /*
2182 * Initialize for prepended IV for block cipher in TLS v1.1 and up
2183 */
2185 {
2186 unsigned char i;
2187 dec_msglen -= ssl->transform_in->ivlen;
2188 ssl->in_msglen -= ssl->transform_in->ivlen;
2189
2190 for( i = 0; i < ssl->transform_in->ivlen; i++ )
2191 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
2192 }
2193#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
2194
2196 ssl->transform_in->iv_dec,
2197 ssl->transform_in->ivlen,
2198 dec_msg, dec_msglen,
2199 dec_msg_result, &olen ) ) != 0 )
2200 {
2201 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
2202 return( ret );
2203 }
2204
2205 if( dec_msglen != olen )
2206 {
2207 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2209 }
2210
2211#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
2213 {
2214 /*
2215 * Save IV in SSL3 and TLS1
2216 */
2217 memcpy( ssl->transform_in->iv_dec,
2219 ssl->transform_in->ivlen );
2220 }
2221#endif
2222
2223 padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
2224
2225 if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
2226 auth_done == 0 )
2227 {
2228#if defined(MBEDTLS_SSL_DEBUG_ALL)
2229 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
2230 ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
2231#endif
2232 padlen = 0;
2233 correct = 0;
2234 }
2235
2236#if defined(MBEDTLS_SSL_PROTO_SSL3)
2238 {
2239 if( padlen > ssl->transform_in->ivlen )
2240 {
2241#if defined(MBEDTLS_SSL_DEBUG_ALL)
2242 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
2243 "should be no more than %d",
2244 padlen, ssl->transform_in->ivlen ) );
2245#endif
2246 correct = 0;
2247 }
2248 }
2249 else
2250#endif /* MBEDTLS_SSL_PROTO_SSL3 */
2251#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2252 defined(MBEDTLS_SSL_PROTO_TLS1_2)
2254 {
2255 /*
2256 * TLSv1+: always check the padding up to the first failure
2257 * and fake check up to 256 bytes of padding
2258 */
2259 size_t pad_count = 0, real_count = 1;
2260 size_t padding_idx = ssl->in_msglen - padlen;
2261 size_t i;
2262
2263 /*
2264 * Padding is guaranteed to be incorrect if:
2265 * 1. padlen > ssl->in_msglen
2266 *
2267 * 2. padding_idx > MBEDTLS_SSL_IN_CONTENT_LEN +
2268 * ssl->transform_in->maclen
2269 *
2270 * In both cases we reset padding_idx to a safe value (0) to
2271 * prevent out-of-buffer reads.
2272 */
2273 correct &= ( padlen <= ssl->in_msglen );
2274 correct &= ( padding_idx <= MBEDTLS_SSL_IN_CONTENT_LEN +
2275 ssl->transform_in->maclen );
2276
2277 padding_idx *= correct;
2278
2279 for( i = 0; i < 256; i++ )
2280 {
2281 real_count &= ( i < padlen );
2282 pad_count += real_count *
2283 ( ssl->in_msg[padding_idx + i] == padlen - 1 );
2284 }
2285
2286 correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
2287
2288#if defined(MBEDTLS_SSL_DEBUG_ALL)
2289 if( padlen > 0 && correct == 0 )
2290 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
2291#endif
2292 padlen &= correct * 0x1FF;
2293 }
2294 else
2295#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2296 MBEDTLS_SSL_PROTO_TLS1_2 */
2297 {
2298 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2300 }
2301
2302 ssl->in_msglen -= padlen;
2303 }
2304 else
2305#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */
2306 {
2307 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2309 }
2310
2311#if defined(MBEDTLS_SSL_DEBUG_ALL)
2312 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
2313 ssl->in_msg, ssl->in_msglen );
2314#endif
2315
2316 /*
2317 * Authenticate if not done yet.
2318 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
2319 */
2320#if defined(SSL_SOME_MODES_USE_MAC)
2321 if( auth_done == 0 )
2322 {
2323 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
2324 unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD];
2325
2326 ssl->in_msglen -= ssl->transform_in->maclen;
2327
2328 ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
2329 ssl->in_len[1] = (unsigned char)( ssl->in_msglen );
2330
2331#if defined(MBEDTLS_SSL_PROTO_SSL3)
2333 {
2334 ssl_mac( &ssl->transform_in->md_ctx_dec,
2335 ssl->transform_in->mac_dec,
2336 ssl->in_msg, ssl->in_msglen,
2337 ssl->in_ctr, ssl->in_msgtype,
2338 mac_expect );
2339 memcpy( mac_peer, ssl->in_msg + ssl->in_msglen,
2340 ssl->transform_in->maclen );
2341 }
2342 else
2343#endif /* MBEDTLS_SSL_PROTO_SSL3 */
2344#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2345 defined(MBEDTLS_SSL_PROTO_TLS1_2)
2347 {
2348 int ret;
2349 unsigned char add_data[13];
2350
2351 /*
2352 * The next two sizes are the minimum and maximum values of
2353 * in_msglen over all padlen values.
2354 *
2355 * They're independent of padlen, since we previously did
2356 * in_msglen -= padlen.
2357 *
2358 * Note that max_len + maclen is never more than the buffer
2359 * length, as we previously did in_msglen -= maclen too.
2360 */
2361 const size_t max_len = ssl->in_msglen + padlen;
2362 const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
2363
2364 memcpy( add_data + 0, ssl->in_ctr, 8 );
2365 memcpy( add_data + 8, ssl->in_hdr, 3 );
2366 memcpy( add_data + 11, ssl->in_len, 2 );
2367
2369 add_data, sizeof( add_data ),
2370 ssl->in_msg, ssl->in_msglen,
2371 min_len, max_len,
2372 mac_expect );
2373 if( ret != 0 )
2374 {
2375 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_cf_hmac", ret );
2376 return( ret );
2377 }
2378
2379 mbedtls_ssl_cf_memcpy_offset( mac_peer, ssl->in_msg,
2380 ssl->in_msglen,
2381 min_len, max_len,
2382 ssl->transform_in->maclen );
2383 }
2384 else
2385#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2386 MBEDTLS_SSL_PROTO_TLS1_2 */
2387 {
2388 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2390 }
2391
2392#if defined(MBEDTLS_SSL_DEBUG_ALL)
2393 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
2394 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, ssl->transform_in->maclen );
2395#endif
2396
2397 if( mbedtls_ssl_safer_memcmp( mac_peer, mac_expect,
2398 ssl->transform_in->maclen ) != 0 )
2399 {
2400#if defined(MBEDTLS_SSL_DEBUG_ALL)
2401 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
2402#endif
2403 correct = 0;
2404 }
2405 auth_done++;
2406 }
2407
2408 /*
2409 * Finally check the correct flag
2410 */
2411 if( correct == 0 )
2413#endif /* SSL_SOME_MODES_USE_MAC */
2414
2415 /* Make extra sure authentication was performed, exactly once */
2416 if( auth_done != 1 )
2417 {
2418 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2420 }
2421
2422 if( ssl->in_msglen == 0 )
2423 {
2424#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2427 {
2428 /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
2429 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
2431 }
2432#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2433
2434 ssl->nb_zero++;
2435
2436 /*
2437 * Three or more empty messages may be a DoS attack
2438 * (excessive CPU consumption).
2439 */
2440 if( ssl->nb_zero > 3 )
2441 {
2442 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
2443 "messages, possible DoS attack" ) );
2445 }
2446 }
2447 else
2448 ssl->nb_zero = 0;
2449
2450#if defined(MBEDTLS_SSL_PROTO_DTLS)
2452 {
2453 ; /* in_ctr read from peer, not maintained internally */
2454 }
2455 else
2456#endif
2457 {
2458 unsigned char i;
2459 for( i = 8; i > ssl_ep_len( ssl ); i-- )
2460 if( ++ssl->in_ctr[i - 1] != 0 )
2461 break;
2462
2463 /* The loop goes to its end iff the counter is wrapping */
2464 if( i == ssl_ep_len( ssl ) )
2465 {
2466 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
2468 }
2469 }
2470
2471 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
2472
2473 return( 0 );
2474}
2475
2476#undef MAC_NONE
2477#undef MAC_PLAINTEXT
2478#undef MAC_CIPHERTEXT
2479
2480#if defined(MBEDTLS_ZLIB_SUPPORT)
2481/*
2482 * Compression/decompression functions
2483 */
2484static int ssl_compress_buf( mbedtls_ssl_context *ssl )
2485{
2486 int ret;
2487 unsigned char *msg_post = ssl->out_msg;
2488 ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
2489 size_t len_pre = ssl->out_msglen;
2490 unsigned char *msg_pre = ssl->compress_buf;
2491
2492 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
2493
2494 if( len_pre == 0 )
2495 return( 0 );
2496
2497 memcpy( msg_pre, ssl->out_msg, len_pre );
2498
2499 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
2500 ssl->out_msglen ) );
2501
2502 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
2503 ssl->out_msg, ssl->out_msglen );
2504
2505 ssl->transform_out->ctx_deflate.next_in = msg_pre;
2506 ssl->transform_out->ctx_deflate.avail_in = len_pre;
2507 ssl->transform_out->ctx_deflate.next_out = msg_post;
2508 ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;
2509
2510 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
2511 if( ret != Z_OK )
2512 {
2513 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
2515 }
2516
2518 ssl->transform_out->ctx_deflate.avail_out - bytes_written;
2519
2520 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
2521 ssl->out_msglen ) );
2522
2523 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
2524 ssl->out_msg, ssl->out_msglen );
2525
2526 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
2527
2528 return( 0 );
2529}
2530
2531static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
2532{
2533 int ret;
2534 unsigned char *msg_post = ssl->in_msg;
2535 ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
2536 size_t len_pre = ssl->in_msglen;
2537 unsigned char *msg_pre = ssl->compress_buf;
2538
2539 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
2540
2541 if( len_pre == 0 )
2542 return( 0 );
2543
2544 memcpy( msg_pre, ssl->in_msg, len_pre );
2545
2546 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
2547 ssl->in_msglen ) );
2548
2549 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
2550 ssl->in_msg, ssl->in_msglen );
2551
2552 ssl->transform_in->ctx_inflate.next_in = msg_pre;
2553 ssl->transform_in->ctx_inflate.avail_in = len_pre;
2554 ssl->transform_in->ctx_inflate.next_out = msg_post;
2555 ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -
2556 header_bytes;
2557
2558 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
2559 if( ret != Z_OK )
2560 {
2561 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
2563 }
2564
2566 ssl->transform_in->ctx_inflate.avail_out - header_bytes;
2567
2568 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
2569 ssl->in_msglen ) );
2570
2571 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
2572 ssl->in_msg, ssl->in_msglen );
2573
2574 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
2575
2576 return( 0 );
2577}
2578#endif /* MBEDTLS_ZLIB_SUPPORT */
2579
2580#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2581static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
2582
2583#if defined(MBEDTLS_SSL_PROTO_DTLS)
2584static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
2585{
2586 /* If renegotiation is not enforced, retransmit until we would reach max
2587 * timeout if we were using the usual handshake doubling scheme */
2588 if( ssl->conf->renego_max_records < 0 )
2589 {
2590 uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2591 unsigned char doublings = 1;
2592
2593 while( ratio != 0 )
2594 {
2595 ++doublings;
2596 ratio >>= 1;
2597 }
2598
2599 if( ++ssl->renego_records_seen > doublings )
2600 {
2601 MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
2602 return( 0 );
2603 }
2604 }
2605
2606 return( ssl_write_hello_request( ssl ) );
2607}
2608#endif
2609#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2610
2611/*
2612 * Fill the input message buffer by appending data to it.
2613 * The amount of data already fetched is in ssl->in_left.
2614 *
2615 * If we return 0, is it guaranteed that (at least) nb_want bytes are
2616 * available (from this read and/or a previous one). Otherwise, an error code
2617 * is returned (possibly EOF or WANT_READ).
2618 *
2619 * With stream transport (TLS) on success ssl->in_left == nb_want, but
2620 * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
2621 * since we always read a whole datagram at once.
2622 *
2623 * For DTLS, it is up to the caller to set ssl->next_record_offset when
2624 * they're done reading a record.
2625 */
2626int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
2627{
2628 int ret;
2629 size_t len;
2630
2631 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
2632
2633 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
2634 {
2635 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2636 "or mbedtls_ssl_set_bio()" ) );
2638 }
2639
2640 if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
2641 {
2642 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
2644 }
2645
2646#if defined(MBEDTLS_SSL_PROTO_DTLS)
2648 {
2650
2651 /* Just to be sure */
2652 if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
2653 {
2654 MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
2655 "mbedtls_ssl_set_timer_cb() for DTLS" ) );
2657 }
2658
2659 /*
2660 * The point is, we need to always read a full datagram at once, so we
2661 * sometimes read more then requested, and handle the additional data.
2662 * It could be the rest of the current record (while fetching the
2663 * header) and/or some other records in the same datagram.
2664 */
2665
2666 /*
2667 * Move to the next record in the already read datagram if applicable
2668 */
2669 if( ssl->next_record_offset != 0 )
2670 {
2671 if( ssl->in_left < ssl->next_record_offset )
2672 {
2673 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2675 }
2676
2677 ssl->in_left -= ssl->next_record_offset;
2678
2679 if( ssl->in_left != 0 )
2680 {
2681 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
2682 ssl->next_record_offset ) );
2683 memmove( ssl->in_hdr,
2684 ssl->in_hdr + ssl->next_record_offset,
2685 ssl->in_left );
2686 }
2687
2688 ssl->next_record_offset = 0;
2689 }
2690
2691 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2692 ssl->in_left, nb_want ) );
2693
2694 /*
2695 * Done if we already have enough data.
2696 */
2697 if( nb_want <= ssl->in_left)
2698 {
2699 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2700 return( 0 );
2701 }
2702
2703 /*
2704 * A record can't be split across datagrams. If we need to read but
2705 * are not at the beginning of a new record, the caller did something
2706 * wrong.
2707 */
2708 if( ssl->in_left != 0 )
2709 {
2710 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2712 }
2713
2714 /*
2715 * Don't even try to read if time's out already.
2716 * This avoids by-passing the timer when repeatedly receiving messages
2717 * that will end up being dropped.
2718 */
2719 if( ssl_check_timer( ssl ) != 0 )
2720 {
2721 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
2723 }
2724 else
2725 {
2726 len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
2727
2728 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2729 timeout = ssl->handshake->retransmit_timeout;
2730 else
2731 timeout = ssl->conf->read_timeout;
2732
2733 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
2734
2735 if( ssl->f_recv_timeout != NULL )
2736 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
2737 timeout );
2738 else
2739 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
2740
2741 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2742
2743 if( ret == 0 )
2744 return( MBEDTLS_ERR_SSL_CONN_EOF );
2745 }
2746
2748 {
2749 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
2750 ssl_set_timer( ssl, 0 );
2751
2752 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
2753 {
2754 if( ssl_double_retransmit_timeout( ssl ) != 0 )
2755 {
2756 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
2757 return( MBEDTLS_ERR_SSL_TIMEOUT );
2758 }
2759
2760 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
2761 {
2762 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
2763 return( ret );
2764 }
2765
2766 return( MBEDTLS_ERR_SSL_WANT_READ );
2767 }
2768#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2769 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
2771 {
2772 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
2773 {
2774 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
2775 return( ret );
2776 }
2777
2778 return( MBEDTLS_ERR_SSL_WANT_READ );
2779 }
2780#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2781 }
2782
2783 if( ret < 0 )
2784 return( ret );
2785
2786 ssl->in_left = ret;
2787 }
2788 else
2789#endif
2790 {
2791 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2792 ssl->in_left, nb_want ) );
2793
2794 while( ssl->in_left < nb_want )
2795 {
2796 len = nb_want - ssl->in_left;
2797
2798 if( ssl_check_timer( ssl ) != 0 )
2800 else
2801 {
2802 if( ssl->f_recv_timeout != NULL )
2803 {
2804 ret = ssl->f_recv_timeout( ssl->p_bio,
2805 ssl->in_hdr + ssl->in_left, len,
2806 ssl->conf->read_timeout );
2807 }
2808 else
2809 {
2810 ret = ssl->f_recv( ssl->p_bio,
2811 ssl->in_hdr + ssl->in_left, len );
2812 }
2813 }
2814
2815 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
2816 ssl->in_left, nb_want ) );
2817 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
2818
2819 if( ret == 0 )
2820 return( MBEDTLS_ERR_SSL_CONN_EOF );
2821
2822 if( ret < 0 )
2823 return( ret );
2824
2825 if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) )
2826 {
2828 ( "f_recv returned %d bytes but only %lu were requested",
2829 ret, (unsigned long)len ) );
2831 }
2832
2833 ssl->in_left += ret;
2834 }
2835 }
2836
2837 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
2838
2839 return( 0 );
2840}
2841
2842/*
2843 * Flush any data not yet written
2844 */
2846{
2847 int ret;
2848 unsigned char *buf;
2849
2850 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
2851
2852 if( ssl->f_send == NULL )
2853 {
2854 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
2855 "or mbedtls_ssl_set_bio()" ) );
2857 }
2858
2859 /* Avoid incrementing counter if data is flushed */
2860 if( ssl->out_left == 0 )
2861 {
2862 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2863 return( 0 );
2864 }
2865
2866 while( ssl->out_left > 0 )
2867 {
2868 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
2869 mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
2870
2871 buf = ssl->out_hdr - ssl->out_left;
2872 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
2873
2874 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
2875
2876 if( ret <= 0 )
2877 return( ret );
2878
2879 if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) )
2880 {
2882 ( "f_send returned %d bytes but only %lu bytes were sent",
2883 ret, (unsigned long)ssl->out_left ) );
2885 }
2886
2887 ssl->out_left -= ret;
2888 }
2889
2890#if defined(MBEDTLS_SSL_PROTO_DTLS)
2892 {
2893 ssl->out_hdr = ssl->out_buf;
2894 }
2895 else
2896#endif
2897 {
2898 ssl->out_hdr = ssl->out_buf + 8;
2899 }
2900 ssl_update_out_pointers( ssl, ssl->transform_out );
2901
2902 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
2903
2904 return( 0 );
2905}
2906
2907/*
2908 * Functions to handle the DTLS retransmission state machine
2909 */
2910#if defined(MBEDTLS_SSL_PROTO_DTLS)
2911/*
2912 * Append current handshake message to current outgoing flight
2913 */
2914static int ssl_flight_append( mbedtls_ssl_context *ssl )
2915{
2916 mbedtls_ssl_flight_item *msg;
2917 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
2918 MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
2919 ssl->out_msg, ssl->out_msglen );
2920
2921 /* Allocate space for current message */
2922 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL )
2923 {
2924 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
2925 sizeof( mbedtls_ssl_flight_item ) ) );
2927 }
2928
2929 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
2930 {
2931 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
2932 mbedtls_free( msg );
2934 }
2935
2936 /* Copy current handshake message with headers */
2937 memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
2938 msg->len = ssl->out_msglen;
2939 msg->type = ssl->out_msgtype;
2940 msg->next = NULL;
2941
2942 /* Append to the current flight */
2943 if( ssl->handshake->flight == NULL )
2944 ssl->handshake->flight = msg;
2945 else
2946 {
2947 mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
2948 while( cur->next != NULL )
2949 cur = cur->next;
2950 cur->next = msg;
2951 }
2952
2953 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
2954 return( 0 );
2955}
2956
2957/*
2958 * Free the current flight of handshake messages
2959 */
2960static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
2961{
2962 mbedtls_ssl_flight_item *cur = flight;
2963 mbedtls_ssl_flight_item *next;
2964
2965 while( cur != NULL )
2966 {
2967 next = cur->next;
2968
2969 mbedtls_free( cur->p );
2970 mbedtls_free( cur );
2971
2972 cur = next;
2973 }
2974}
2975
2976#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
2977static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
2978#endif
2979
2980/*
2981 * Swap transform_out and out_ctr with the alternative ones
2982 */
2983static int ssl_swap_epochs( mbedtls_ssl_context *ssl )
2984{
2985 mbedtls_ssl_transform *tmp_transform;
2986 unsigned char tmp_out_ctr[8];
2987#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
2988 int ret;
2989#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
2990
2991 if( ssl->transform_out == ssl->handshake->alt_transform_out )
2992 {
2993 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
2994 return( 0 );
2995 }
2996
2997 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
2998
2999 /* Swap transforms */
3000 tmp_transform = ssl->transform_out;
3001 ssl->transform_out = ssl->handshake->alt_transform_out;
3002 ssl->handshake->alt_transform_out = tmp_transform;
3003
3004 /* Swap epoch + sequence_number */
3005 memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 );
3006 memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 );
3007 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 );
3008
3009 /* Adjust to the newly activated transform */
3010 ssl_update_out_pointers( ssl, ssl->transform_out );
3011
3012#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3013 if( mbedtls_ssl_hw_record_activate != NULL )
3014 {
3015 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
3016 {
3017 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
3019 }
3020 }
3021#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
3022
3023 return( 0 );
3024}
3025
3026/*
3027 * Retransmit the current flight of messages.
3028 */
3029int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
3030{
3031 int ret = 0;
3032
3033 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
3034
3035 ret = mbedtls_ssl_flight_transmit( ssl );
3036
3037 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
3038
3039 return( ret );
3040}
3041
3042/*
3043 * Transmit or retransmit the current flight of messages.
3044 *
3045 * Need to remember the current message in case flush_output returns
3046 * WANT_WRITE, causing us to exit this function and come back later.
3047 * This function must be called until state is no longer SENDING.
3048 */
3049int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
3050{
3051 int ret;
3052 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
3053
3054 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
3055 {
3056 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
3057
3058 ssl->handshake->cur_msg = ssl->handshake->flight;
3059 ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
3060 if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
3061 return( ret );
3062
3063 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
3064 }
3065
3066 while( ssl->handshake->cur_msg != NULL )
3067 {
3068 size_t max_frag_len;
3069 const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
3070
3071 int const is_finished =
3072 ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
3073 cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
3074
3075 uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
3076 SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
3077
3078 /* Swap epochs before sending Finished: we can't do it after
3079 * sending ChangeCipherSpec, in case write returns WANT_READ.
3080 * Must be done before copying, may change out_msg pointer */
3081 if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
3082 {
3083 MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
3084 if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
3085 return( ret );
3086 }
3087
3088 ret = ssl_get_remaining_payload_in_datagram( ssl );
3089 if( ret < 0 )
3090 return( ret );
3091 max_frag_len = (size_t) ret;
3092
3093 /* CCS is copied as is, while HS messages may need fragmentation */
3095 {
3096 if( max_frag_len == 0 )
3097 {
3098 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3099 return( ret );
3100
3101 continue;
3102 }
3103
3104 memcpy( ssl->out_msg, cur->p, cur->len );
3105 ssl->out_msglen = cur->len;
3106 ssl->out_msgtype = cur->type;
3107
3108 /* Update position inside current message */
3109 ssl->handshake->cur_msg_p += cur->len;
3110 }
3111 else
3112 {
3113 const unsigned char * const p = ssl->handshake->cur_msg_p;
3114 const size_t hs_len = cur->len - 12;
3115 const size_t frag_off = p - ( cur->p + 12 );
3116 const size_t rem_len = hs_len - frag_off;
3117 size_t cur_hs_frag_len, max_hs_frag_len;
3118
3119 if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
3120 {
3121 if( is_finished )
3122 {
3123 if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
3124 return( ret );
3125 }
3126
3127 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3128 return( ret );
3129
3130 continue;
3131 }
3132 max_hs_frag_len = max_frag_len - 12;
3133
3134 cur_hs_frag_len = rem_len > max_hs_frag_len ?
3135 max_hs_frag_len : rem_len;
3136
3137 if( frag_off == 0 && cur_hs_frag_len != hs_len )
3138 {
3139 MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
3140 (unsigned) cur_hs_frag_len,
3141 (unsigned) max_hs_frag_len ) );
3142 }
3143
3144 /* Messages are stored with handshake headers as if not fragmented,
3145 * copy beginning of headers then fill fragmentation fields.
3146 * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
3147 memcpy( ssl->out_msg, cur->p, 6 );
3148
3149 ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
3150 ssl->out_msg[7] = ( ( frag_off >> 8 ) & 0xff );
3151 ssl->out_msg[8] = ( ( frag_off ) & 0xff );
3152
3153 ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
3154 ssl->out_msg[10] = ( ( cur_hs_frag_len >> 8 ) & 0xff );
3155 ssl->out_msg[11] = ( ( cur_hs_frag_len ) & 0xff );
3156
3157 MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
3158
3159 /* Copy the handshake message content and set records fields */
3160 memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
3161 ssl->out_msglen = cur_hs_frag_len + 12;
3162 ssl->out_msgtype = cur->type;
3163
3164 /* Update position inside current message */
3165 ssl->handshake->cur_msg_p += cur_hs_frag_len;
3166 }
3167
3168 /* If done with the current message move to the next one if any */
3169 if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
3170 {
3171 if( cur->next != NULL )
3172 {
3173 ssl->handshake->cur_msg = cur->next;
3174 ssl->handshake->cur_msg_p = cur->next->p + 12;
3175 }
3176 else
3177 {
3178 ssl->handshake->cur_msg = NULL;
3179 ssl->handshake->cur_msg_p = NULL;
3180 }
3181 }
3182
3183 /* Actually send the message out */
3184 if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
3185 {
3186 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
3187 return( ret );
3188 }
3189 }
3190
3191 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3192 return( ret );
3193
3194 /* Update state and set timer */
3195 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
3196 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
3197 else
3198 {
3199 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
3200 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
3201 }
3202
3203 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
3204
3205 return( 0 );
3206}
3207
3208/*
3209 * To be called when the last message of an incoming flight is received.
3210 */
3211void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
3212{
3213 /* We won't need to resend that one any more */
3214 ssl_flight_free( ssl->handshake->flight );
3215 ssl->handshake->flight = NULL;
3216 ssl->handshake->cur_msg = NULL;
3217
3218 /* The next incoming flight will start with this msg_seq */
3219 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
3220
3221 /* We don't want to remember CCS's across flight boundaries. */
3222 ssl->handshake->buffering.seen_ccs = 0;
3223
3224 /* Clear future message buffering structure. */
3225 ssl_buffering_free( ssl );
3226
3227 /* Cancel timer */
3228 ssl_set_timer( ssl, 0 );
3229
3231 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
3232 {
3233 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
3234 }
3235 else
3236 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
3237}
3238
3239/*
3240 * To be called when the last message of an outgoing flight is send.
3241 */
3242void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
3243{
3244 ssl_reset_retransmit_timeout( ssl );
3245 ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
3246
3248 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
3249 {
3250 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
3251 }
3252 else
3253 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
3254}
3255#endif /* MBEDTLS_SSL_PROTO_DTLS */
3256
3257/*
3258 * Handshake layer functions
3259 */
3260
3261/*
3262 * Write (DTLS: or queue) current handshake (including CCS) message.
3263 *
3264 * - fill in handshake headers
3265 * - update handshake checksum
3266 * - DTLS: save message for resending
3267 * - then pass to the record layer
3268 *
3269 * DTLS: except for HelloRequest, messages are only queued, and will only be
3270 * actually sent when calling flight_transmit() or resend().
3271 *
3272 * Inputs:
3273 * - ssl->out_msglen: 4 + actual handshake message len
3274 * (4 is the size of handshake headers for TLS)
3275 * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
3276 * - ssl->out_msg + 4: the handshake message body
3277 *
3278 * Outputs, ie state before passing to flight_append() or write_record():
3279 * - ssl->out_msglen: the length of the record contents
3280 * (including handshake headers but excluding record headers)
3281 * - ssl->out_msg: the record contents (handshake headers + content)
3282 */
3284{
3285 int ret;
3286 const size_t hs_len = ssl->out_msglen - 4;
3287 const unsigned char hs_type = ssl->out_msg[0];
3288
3289 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
3290
3291 /*
3292 * Sanity checks
3293 */
3296 {
3297 /* In SSLv3, the client might send a NoCertificate alert. */
3298#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
3299 if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
3302#endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
3303 {
3304 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3306 }
3307 }
3308
3309 /* Whenever we send anything different from a
3310 * HelloRequest we should be in a handshake - double check. */
3311 if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3312 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) &&
3313 ssl->handshake == NULL )
3314 {
3315 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3317 }
3318
3319#if defined(MBEDTLS_SSL_PROTO_DTLS)
3321 ssl->handshake != NULL &&
3322 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
3323 {
3324 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3326 }
3327#endif
3328
3329 /* Double-check that we did not exceed the bounds
3330 * of the outgoing record buffer.
3331 * This should never fail as the various message
3332 * writing functions must obey the bounds of the
3333 * outgoing record buffer, but better be safe.
3334 *
3335 * Note: We deliberately do not check for the MTU or MFL here.
3336 */
3338 {
3339 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
3340 "size %u, maximum %u",
3341 (unsigned) ssl->out_msglen,
3342 (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
3344 }
3345
3346 /*
3347 * Fill handshake headers
3348 */
3350 {
3351 ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
3352 ssl->out_msg[2] = (unsigned char)( hs_len >> 8 );
3353 ssl->out_msg[3] = (unsigned char)( hs_len );
3354
3355 /*
3356 * DTLS has additional fields in the Handshake layer,
3357 * between the length field and the actual payload:
3358 * uint16 message_seq;
3359 * uint24 fragment_offset;
3360 * uint24 fragment_length;
3361 */
3362#if defined(MBEDTLS_SSL_PROTO_DTLS)
3364 {
3365 /* Make room for the additional DTLS fields */
3367 {
3368 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
3369 "size %u, maximum %u",
3370 (unsigned) ( hs_len ),
3371 (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
3373 }
3374
3375 memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
3376 ssl->out_msglen += 8;
3377
3378 /* Write message_seq and update it, except for HelloRequest */
3379 if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
3380 {
3381 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
3382 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF;
3383 ++( ssl->handshake->out_msg_seq );
3384 }
3385 else
3386 {
3387 ssl->out_msg[4] = 0;
3388 ssl->out_msg[5] = 0;
3389 }
3390
3391 /* Handshake hashes are computed without fragmentation,
3392 * so set frag_offset = 0 and frag_len = hs_len for now */
3393 memset( ssl->out_msg + 6, 0x00, 3 );
3394 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
3395 }
3396#endif /* MBEDTLS_SSL_PROTO_DTLS */
3397
3398 /* Update running hashes of handshake messages seen */
3399 if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
3400 ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
3401 }
3402
3403 /* Either send now, or just save to be sent (and resent) later */
3404#if defined(MBEDTLS_SSL_PROTO_DTLS)
3407 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) )
3408 {
3409 if( ( ret = ssl_flight_append( ssl ) ) != 0 )
3410 {
3411 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
3412 return( ret );
3413 }
3414 }
3415 else
3416#endif
3417 {
3418 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
3419 {
3420 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
3421 return( ret );
3422 }
3423 }
3424
3425 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
3426
3427 return( 0 );
3428}
3429
3430/*
3431 * Record layer functions
3432 */
3433
3434/*
3435 * Write current record.
3436 *
3437 * Uses:
3438 * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
3439 * - ssl->out_msglen: length of the record content (excl headers)
3440 * - ssl->out_msg: record content
3441 */
3443{
3444 int ret, done = 0;
3445 size_t len = ssl->out_msglen;
3446 uint8_t flush = force_flush;
3447
3448 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
3449
3450#if defined(MBEDTLS_ZLIB_SUPPORT)
3451 if( ssl->transform_out != NULL &&
3453 {
3454 if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
3455 {
3456 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
3457 return( ret );
3458 }
3459
3460 len = ssl->out_msglen;
3461 }
3462#endif /*MBEDTLS_ZLIB_SUPPORT */
3463
3464#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3465 if( mbedtls_ssl_hw_record_write != NULL )
3466 {
3467 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
3468
3469 ret = mbedtls_ssl_hw_record_write( ssl );
3471 {
3472 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
3474 }
3475
3476 if( ret == 0 )
3477 done = 1;
3478 }
3479#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
3480 if( !done )
3481 {
3482 unsigned i;
3483 size_t protected_record_size;
3484
3485 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
3487 ssl->conf->transport, ssl->out_hdr + 1 );
3488
3489 memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
3490 ssl->out_len[0] = (unsigned char)( len >> 8 );
3491 ssl->out_len[1] = (unsigned char)( len );
3492
3493 if( ssl->transform_out != NULL )
3494 {
3495 if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
3496 {
3497 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
3498 return( ret );
3499 }
3500
3501 len = ssl->out_msglen;
3502 ssl->out_len[0] = (unsigned char)( len >> 8 );
3503 ssl->out_len[1] = (unsigned char)( len );
3504 }
3505
3506 protected_record_size = len + mbedtls_ssl_hdr_len( ssl );
3507
3508#if defined(MBEDTLS_SSL_PROTO_DTLS)
3509 /* In case of DTLS, double-check that we don't exceed
3510 * the remaining space in the datagram. */
3512 {
3513 ret = ssl_get_remaining_space_in_datagram( ssl );
3514 if( ret < 0 )
3515 return( ret );
3516
3517 if( protected_record_size > (size_t) ret )
3518 {
3519 /* Should never happen */
3521 }
3522 }
3523#endif /* MBEDTLS_SSL_PROTO_DTLS */
3524
3525 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
3526 "version = [%d:%d], msglen = %d",
3527 ssl->out_hdr[0], ssl->out_hdr[1],
3528 ssl->out_hdr[2], len ) );
3529
3530 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
3531 ssl->out_hdr, protected_record_size );
3532
3533 ssl->out_left += protected_record_size;
3534 ssl->out_hdr += protected_record_size;
3535 ssl_update_out_pointers( ssl, ssl->transform_out );
3536
3537 for( i = 8; i > ssl_ep_len( ssl ); i-- )
3538 if( ++ssl->cur_out_ctr[i - 1] != 0 )
3539 break;
3540
3541 /* The loop goes to its end iff the counter is wrapping */
3542 if( i == ssl_ep_len( ssl ) )
3543 {
3544 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
3546 }
3547 }
3548
3549#if defined(MBEDTLS_SSL_PROTO_DTLS)
3551 flush == SSL_DONT_FORCE_FLUSH )
3552 {
3553 size_t remaining;
3554 ret = ssl_get_remaining_payload_in_datagram( ssl );
3555 if( ret < 0 )
3556 {
3557 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
3558 ret );
3559 return( ret );
3560 }
3561
3562 remaining = (size_t) ret;
3563 if( remaining == 0 )
3564 {
3565 flush = SSL_FORCE_FLUSH;
3566 }
3567 else
3568 {
3569 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
3570 }
3571 }
3572#endif /* MBEDTLS_SSL_PROTO_DTLS */
3573
3574 if( ( flush == SSL_FORCE_FLUSH ) &&
3575 ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3576 {
3577 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
3578 return( ret );
3579 }
3580
3581 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
3582
3583 return( 0 );
3584}
3585
3586#if defined(MBEDTLS_SSL_PROTO_DTLS)
3587
3588static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
3589{
3590 if( ssl->in_msglen < ssl->in_hslen ||
3591 memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 ||
3592 memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
3593 {
3594 return( 1 );
3595 }
3596 return( 0 );
3597}
3598
3599static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
3600{
3601 return( ( ssl->in_msg[9] << 16 ) |
3602 ( ssl->in_msg[10] << 8 ) |
3603 ssl->in_msg[11] );
3604}
3605
3606static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
3607{
3608 return( ( ssl->in_msg[6] << 16 ) |
3609 ( ssl->in_msg[7] << 8 ) |
3610 ssl->in_msg[8] );
3611}
3612
3613static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
3614{
3615 uint32_t msg_len, frag_off, frag_len;
3616
3617 msg_len = ssl_get_hs_total_len( ssl );
3618 frag_off = ssl_get_hs_frag_off( ssl );
3619 frag_len = ssl_get_hs_frag_len( ssl );
3620
3621 if( frag_off > msg_len )
3622 return( -1 );
3623
3624 if( frag_len > msg_len - frag_off )
3625 return( -1 );
3626
3627 if( frag_len + 12 > ssl->in_msglen )
3628 return( -1 );
3629
3630 return( 0 );
3631}
3632
3633/*
3634 * Mark bits in bitmask (used for DTLS HS reassembly)
3635 */
3636static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
3637{
3638 unsigned int start_bits, end_bits;
3639
3640 start_bits = 8 - ( offset % 8 );
3641 if( start_bits != 8 )
3642 {
3643 size_t first_byte_idx = offset / 8;
3644
3645 /* Special case */
3646 if( len <= start_bits )
3647 {
3648 for( ; len != 0; len-- )
3649 mask[first_byte_idx] |= 1 << ( start_bits - len );
3650
3651 /* Avoid potential issues with offset or len becoming invalid */
3652 return;
3653 }
3654
3655 offset += start_bits; /* Now offset % 8 == 0 */
3656 len -= start_bits;
3657
3658 for( ; start_bits != 0; start_bits-- )
3659 mask[first_byte_idx] |= 1 << ( start_bits - 1 );
3660 }
3661
3662 end_bits = len % 8;
3663 if( end_bits != 0 )
3664 {
3665 size_t last_byte_idx = ( offset + len ) / 8;
3666
3667 len -= end_bits; /* Now len % 8 == 0 */
3668
3669 for( ; end_bits != 0; end_bits-- )
3670 mask[last_byte_idx] |= 1 << ( 8 - end_bits );
3671 }
3672
3673 memset( mask + offset / 8, 0xFF, len / 8 );
3674}
3675
3676/*
3677 * Check that bitmask is full
3678 */
3679static int ssl_bitmask_check( unsigned char *mask, size_t len )
3680{
3681 size_t i;
3682
3683 for( i = 0; i < len / 8; i++ )
3684 if( mask[i] != 0xFF )
3685 return( -1 );
3686
3687 for( i = 0; i < len % 8; i++ )
3688 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
3689 return( -1 );
3690
3691 return( 0 );
3692}
3693
3694/* msg_len does not include the handshake header */
3695static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
3696 unsigned add_bitmap )
3697{
3698 size_t alloc_len;
3699
3700 alloc_len = 12; /* Handshake header */
3701 alloc_len += msg_len; /* Content buffer */
3702
3703 if( add_bitmap )
3704 alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */
3705
3706 return( alloc_len );
3707}
3708
3709#endif /* MBEDTLS_SSL_PROTO_DTLS */
3710
3711static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
3712{
3713 return( ( ssl->in_msg[1] << 16 ) |
3714 ( ssl->in_msg[2] << 8 ) |
3715 ssl->in_msg[3] );
3716}
3717
3719{
3720 if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
3721 {
3722 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
3723 ssl->in_msglen ) );
3725 }
3726
3727 ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
3728
3729 MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
3730 " %d, type = %d, hslen = %d",
3731 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
3732
3733#if defined(MBEDTLS_SSL_PROTO_DTLS)
3735 {
3736 int ret;
3737 unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
3738
3739 if( ssl_check_hs_header( ssl ) != 0 )
3740 {
3741 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
3743 }
3744
3745 if( ssl->handshake != NULL &&
3746 ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
3747 recv_msg_seq != ssl->handshake->in_msg_seq ) ||
3749 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
3750 {
3751 if( recv_msg_seq > ssl->handshake->in_msg_seq )
3752 {
3753 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
3754 recv_msg_seq,
3755 ssl->handshake->in_msg_seq ) );
3757 }
3758
3759 /* Retransmit only on last message from previous flight, to avoid
3760 * too many retransmissions.
3761 * Besides, No sane server ever retransmits HelloVerifyRequest */
3762 if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
3764 {
3765 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
3766 "message_seq = %d, start_of_flight = %d",
3767 recv_msg_seq,
3768 ssl->handshake->in_flight_start_seq ) );
3769
3770 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3771 {
3772 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
3773 return( ret );
3774 }
3775 }
3776 else
3777 {
3778 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
3779 "message_seq = %d, expected = %d",
3780 recv_msg_seq,
3781 ssl->handshake->in_msg_seq ) );
3782 }
3783
3785 }
3786 /* Wait until message completion to increment in_msg_seq */
3787
3788 /* Message reassembly is handled alongside buffering of future
3789 * messages; the commonality is that both handshake fragments and
3790 * future messages cannot be forwarded immediately to the
3791 * handshake logic layer. */
3792 if( ssl_hs_is_proper_fragment( ssl ) == 1 )
3793 {
3794 MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
3796 }
3797 }
3798 else
3799#endif /* MBEDTLS_SSL_PROTO_DTLS */
3800 /* With TLS we don't handle fragmentation (for now) */
3801 if( ssl->in_msglen < ssl->in_hslen )
3802 {
3803 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
3805 }
3806
3807 return( 0 );
3808}
3809
3811{
3812 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
3813
3814 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
3815 {
3816 ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
3817 }
3818
3819 /* Handshake message is complete, increment counter */
3820#if defined(MBEDTLS_SSL_PROTO_DTLS)
3822 ssl->handshake != NULL )
3823 {
3824 unsigned offset;
3825 mbedtls_ssl_hs_buffer *hs_buf;
3826
3827 /* Increment handshake sequence number */
3828 hs->in_msg_seq++;
3829
3830 /*
3831 * Clear up handshake buffering and reassembly structure.
3832 */
3833
3834 /* Free first entry */
3835 ssl_buffering_free_slot( ssl, 0 );
3836
3837 /* Shift all other entries */
3838 for( offset = 0, hs_buf = &hs->buffering.hs[0];
3840 offset++, hs_buf++ )
3841 {
3842 *hs_buf = *(hs_buf + 1);
3843 }
3844
3845 /* Create a fresh last entry */
3846 memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
3847 }
3848#endif
3849}
3850
3851/*
3852 * DTLS anti-replay: RFC 6347 4.1.2.6
3853 *
3854 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
3855 * Bit n is set iff record number in_window_top - n has been seen.
3856 *
3857 * Usually, in_window_top is the last record number seen and the lsb of
3858 * in_window is set. The only exception is the initial state (record number 0
3859 * not seen yet).
3860 */
3861#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3862static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
3863{
3864 ssl->in_window_top = 0;
3865 ssl->in_window = 0;
3866}
3867
3868static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
3869{
3870 return( ( (uint64_t) buf[0] << 40 ) |
3871 ( (uint64_t) buf[1] << 32 ) |
3872 ( (uint64_t) buf[2] << 24 ) |
3873 ( (uint64_t) buf[3] << 16 ) |
3874 ( (uint64_t) buf[4] << 8 ) |
3875 ( (uint64_t) buf[5] ) );
3876}
3877
3878/*
3879 * Return 0 if sequence number is acceptable, -1 otherwise
3880 */
3881int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
3882{
3883 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3884 uint64_t bit;
3885
3886 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3887 return( 0 );
3888
3889 if( rec_seqnum > ssl->in_window_top )
3890 return( 0 );
3891
3892 bit = ssl->in_window_top - rec_seqnum;
3893
3894 if( bit >= 64 )
3895 return( -1 );
3896
3897 if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
3898 return( -1 );
3899
3900 return( 0 );
3901}
3902
3903/*
3904 * Update replay window on new validated record
3905 */
3906void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
3907{
3908 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
3909
3910 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
3911 return;
3912
3913 if( rec_seqnum > ssl->in_window_top )
3914 {
3915 /* Update window_top and the contents of the window */
3916 uint64_t shift = rec_seqnum - ssl->in_window_top;
3917
3918 if( shift >= 64 )
3919 ssl->in_window = 1;
3920 else
3921 {
3922 ssl->in_window <<= shift;
3923 ssl->in_window |= 1;
3924 }
3925
3926 ssl->in_window_top = rec_seqnum;
3927 }
3928 else
3929 {
3930 /* Mark that number as seen in the current window */
3931 uint64_t bit = ssl->in_window_top - rec_seqnum;
3932
3933 if( bit < 64 ) /* Always true, but be extra sure */
3934 ssl->in_window |= (uint64_t) 1 << bit;
3935 }
3936}
3937#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
3938
3939#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3940/* Forward declaration */
3941static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
3942
3943/*
3944 * Without any SSL context, check if a datagram looks like a ClientHello with
3945 * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
3946 * Both input and output include full DTLS headers.
3947 *
3948 * - if cookie is valid, return 0
3949 * - if ClientHello looks superficially valid but cookie is not,
3950 * fill obuf and set olen, then
3951 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
3952 * - otherwise return a specific error code
3953 */
3954static int ssl_check_dtls_clihlo_cookie(
3955 mbedtls_ssl_cookie_write_t *f_cookie_write,
3956 mbedtls_ssl_cookie_check_t *f_cookie_check,
3957 void *p_cookie,
3958 const unsigned char *cli_id, size_t cli_id_len,
3959 const unsigned char *in, size_t in_len,
3960 unsigned char *obuf, size_t buf_len, size_t *olen )
3961{
3962 size_t sid_len, cookie_len;
3963 unsigned char *p;
3964
3965 if( f_cookie_write == NULL || f_cookie_check == NULL )
3967
3968 /*
3969 * Structure of ClientHello with record and handshake headers,
3970 * and expected values. We don't need to check a lot, more checks will be
3971 * done when actually parsing the ClientHello - skipping those checks
3972 * avoids code duplication and does not make cookie forging any easier.
3973 *
3974 * 0-0 ContentType type; copied, must be handshake
3975 * 1-2 ProtocolVersion version; copied
3976 * 3-4 uint16 epoch; copied, must be 0
3977 * 5-10 uint48 sequence_number; copied
3978 * 11-12 uint16 length; (ignored)
3979 *
3980 * 13-13 HandshakeType msg_type; (ignored)
3981 * 14-16 uint24 length; (ignored)
3982 * 17-18 uint16 message_seq; copied
3983 * 19-21 uint24 fragment_offset; copied, must be 0
3984 * 22-24 uint24 fragment_length; (ignored)
3985 *
3986 * 25-26 ProtocolVersion client_version; (ignored)
3987 * 27-58 Random random; (ignored)
3988 * 59-xx SessionID session_id; 1 byte len + sid_len content
3989 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content
3990 * ...
3991 *
3992 * Minimum length is 61 bytes.
3993 */
3994 if( in_len < 61 ||
3996 in[3] != 0 || in[4] != 0 ||
3997 in[19] != 0 || in[20] != 0 || in[21] != 0 )
3998 {
4000 }
4001
4002 sid_len = in[59];
4003 if( sid_len > in_len - 61 )
4005
4006 cookie_len = in[60 + sid_len];
4007 if( cookie_len > in_len - 60 )
4009
4010 if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
4011 cli_id, cli_id_len ) == 0 )
4012 {
4013 /* Valid cookie */
4014 return( 0 );
4015 }
4016
4017 /*
4018 * If we get here, we've got an invalid cookie, let's prepare HVR.
4019 *
4020 * 0-0 ContentType type; copied
4021 * 1-2 ProtocolVersion version; copied
4022 * 3-4 uint16 epoch; copied
4023 * 5-10 uint48 sequence_number; copied
4024 * 11-12 uint16 length; olen - 13
4025 *
4026 * 13-13 HandshakeType msg_type; hello_verify_request
4027 * 14-16 uint24 length; olen - 25
4028 * 17-18 uint16 message_seq; copied
4029 * 19-21 uint24 fragment_offset; copied
4030 * 22-24 uint24 fragment_length; olen - 25
4031 *
4032 * 25-26 ProtocolVersion server_version; 0xfe 0xff
4033 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie
4034 *
4035 * Minimum length is 28.
4036 */
4037 if( buf_len < 28 )
4039
4040 /* Copy most fields and adapt others */
4041 memcpy( obuf, in, 25 );
4043 obuf[25] = 0xfe;
4044 obuf[26] = 0xff;
4045
4046 /* Generate and write actual cookie */
4047 p = obuf + 28;
4048 if( f_cookie_write( p_cookie,
4049 &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
4050 {
4052 }
4053
4054 *olen = p - obuf;
4055
4056 /* Go back and fill length fields */
4057 obuf[27] = (unsigned char)( *olen - 28 );
4058
4059 obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
4060 obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 );
4061 obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) );
4062
4063 obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 );
4064 obuf[12] = (unsigned char)( ( *olen - 13 ) );
4065
4067}
4068
4069/*
4070 * Handle possible client reconnect with the same UDP quadruplet
4071 * (RFC 6347 Section 4.2.8).
4072 *
4073 * Called by ssl_parse_record_header() in case we receive an epoch 0 record
4074 * that looks like a ClientHello.
4075 *
4076 * - if the input looks like a ClientHello without cookies,
4077 * send back HelloVerifyRequest, then
4078 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
4079 * - if the input looks like a ClientHello with a valid cookie,
4080 * reset the session of the current context, and
4081 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
4082 * - if anything goes wrong, return a specific error code
4083 *
4084 * mbedtls_ssl_read_record() will ignore the record if anything else than
4085 * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
4086 * cannot not return 0.
4087 */
4088static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
4089{
4090 int ret;
4091 size_t len;
4092
4093 ret = ssl_check_dtls_clihlo_cookie(
4094 ssl->conf->f_cookie_write,
4095 ssl->conf->f_cookie_check,
4096 ssl->conf->p_cookie,
4097 ssl->cli_id, ssl->cli_id_len,
4098 ssl->in_buf, ssl->in_left,
4100
4101 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
4102
4104 {
4105 int send_ret;
4106 MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) );
4107 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
4108 ssl->out_buf, len );
4109 /* Don't check write errors as we can't do anything here.
4110 * If the error is permanent we'll catch it later,
4111 * if it's not, then hopefully it'll work next time. */
4112 send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len );
4113 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret );
4114 (void) send_ret;
4115
4117 }
4118
4119 if( ret == 0 )
4120 {
4121 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) );
4122 if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
4123 {
4124 MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
4125 return( ret );
4126 }
4127
4129 }
4130
4131 return( ret );
4132}
4133#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
4134
4135/*
4136 * ContentType type;
4137 * ProtocolVersion version;
4138 * uint16 epoch; // DTLS only
4139 * uint48 sequence_number; // DTLS only
4140 * uint16 length;
4141 *
4142 * Return 0 if header looks sane (and, for DTLS, the record is expected)
4143 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
4144 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
4145 *
4146 * With DTLS, mbedtls_ssl_read_record() will:
4147 * 1. proceed with the record if this function returns 0
4148 * 2. drop only the current record if this function returns UNEXPECTED_RECORD
4149 * 3. return CLIENT_RECONNECT if this function return that value
4150 * 4. drop the whole datagram if this function returns anything else.
4151 * Point 2 is needed when the peer is resending, and we have already received
4152 * the first record from a datagram but are still waiting for the others.
4153 */
4154static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
4155{
4156 int major_ver, minor_ver;
4157
4158 MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
4159
4160 ssl->in_msgtype = ssl->in_hdr[0];
4161 ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
4162 mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
4163
4164 MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
4165 "version = [%d:%d], msglen = %d",
4166 ssl->in_msgtype,
4167 major_ver, minor_ver, ssl->in_msglen ) );
4168
4169 /* Check record type */
4174 {
4175 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
4176
4177#if defined(MBEDTLS_SSL_PROTO_DTLS)
4178 /* Silently ignore invalid DTLS records as recommended by RFC 6347
4179 * Section 4.1.2.7 */
4181#endif /* MBEDTLS_SSL_PROTO_DTLS */
4184
4186 }
4187
4188 /* Check version */
4189 if( major_ver != ssl->major_ver )
4190 {
4191 MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
4193 }
4194
4195 if( minor_ver > ssl->conf->max_minor_ver )
4196 {
4197 MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
4199 }
4200
4201 /* Check length against the size of our buffer */
4203 - (size_t)( ssl->in_msg - ssl->in_buf ) )
4204 {
4205 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4207 }
4208
4209 /*
4210 * DTLS-related tests.
4211 * Check epoch before checking length constraint because
4212 * the latter varies with the epoch. E.g., if a ChangeCipherSpec
4213 * message gets duplicated before the corresponding Finished message,
4214 * the second ChangeCipherSpec should be discarded because it belongs
4215 * to an old epoch, but not because its length is shorter than
4216 * the minimum record length for packets using the new record transform.
4217 * Note that these two kinds of failures are handled differently,
4218 * as an unexpected record is silently skipped but an invalid
4219 * record leads to the entire datagram being dropped.
4220 */
4221#if defined(MBEDTLS_SSL_PROTO_DTLS)
4223 {
4224 unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
4225
4226 /* Check epoch (and sequence number) with DTLS */
4227 if( rec_epoch != ssl->in_epoch )
4228 {
4229 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
4230 "expected %d, received %d",
4231 ssl->in_epoch, rec_epoch ) );
4232
4233#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
4234 /*
4235 * Check for an epoch 0 ClientHello. We can't use in_msg here to
4236 * access the first byte of record content (handshake type), as we
4237 * have an active transform (possibly iv_len != 0), so use the
4238 * fact that the record header len is 13 instead.
4239 */
4240 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4242 rec_epoch == 0 &&
4244 ssl->in_left > 13 &&
4246 {
4247 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
4248 "from the same port" ) );
4249 return( ssl_handle_possible_reconnect( ssl ) );
4250 }
4251 else
4252#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
4253 {
4254 /* Consider buffering the record. */
4255 if( rec_epoch == (unsigned int) ssl->in_epoch + 1 )
4256 {
4257 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
4259 }
4260
4262 }
4263 }
4264
4265#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4266 /* Replay detection only works for the current epoch */
4267 if( rec_epoch == ssl->in_epoch &&
4268 mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
4269 {
4270 MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
4272 }
4273#endif
4274
4275 /* Drop unexpected ApplicationData records,
4276 * except at the beginning of renegotiations */
4279#if defined(MBEDTLS_SSL_RENEGOTIATION)
4282#endif
4283 )
4284 {
4285 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
4287 }
4288 }
4289#endif /* MBEDTLS_SSL_PROTO_DTLS */
4290
4291
4292 /* Check length against bounds of the current transform and version */
4293 if( ssl->transform_in == NULL )
4294 {
4295 if( ssl->in_msglen < 1 ||
4297 {
4298 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4300 }
4301 }
4302 else
4303 {
4304 if( ssl->in_msglen < ssl->transform_in->minlen )
4305 {
4306 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4308 }
4309
4310#if defined(MBEDTLS_SSL_PROTO_SSL3)
4313 {
4314 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4316 }
4317#endif
4318#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
4319 defined(MBEDTLS_SSL_PROTO_TLS1_2)
4320 /*
4321 * TLS encrypted messages can have up to 256 bytes of padding
4322 */
4324 ssl->in_msglen > ssl->transform_in->minlen +
4326 {
4327 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4329 }
4330#endif
4331 }
4332
4333 return( 0 );
4334}
4335
4336/*
4337 * If applicable, decrypt (and decompress) record content
4338 */
4339static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
4340{
4341 int ret, done = 0;
4342
4343 MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
4344 ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
4345
4346#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
4347 if( mbedtls_ssl_hw_record_read != NULL )
4348 {
4349 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
4350
4351 ret = mbedtls_ssl_hw_record_read( ssl );
4353 {
4354 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
4356 }
4357
4358 if( ret == 0 )
4359 done = 1;
4360 }
4361#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
4362 if( !done && ssl->transform_in != NULL )
4363 {
4364 if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
4365 {
4366 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
4367 return( ret );
4368 }
4369
4370 MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
4371 ssl->in_msg, ssl->in_msglen );
4372
4374 {
4375 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
4377 }
4378 }
4379
4380#if defined(MBEDTLS_ZLIB_SUPPORT)
4381 if( ssl->transform_in != NULL &&
4383 {
4384 if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
4385 {
4386 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
4387 return( ret );
4388 }
4389 }
4390#endif /* MBEDTLS_ZLIB_SUPPORT */
4391
4392#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4394 {
4395 mbedtls_ssl_dtls_replay_update( ssl );
4396 }
4397#endif
4398
4399 return( 0 );
4400}
4401
4402static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
4403
4404/*
4405 * Read a record.
4406 *
4407 * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
4408 * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
4409 *
4410 */
4411
4412/* Helper functions for mbedtls_ssl_read_record(). */
4413static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
4414static int ssl_get_next_record( mbedtls_ssl_context *ssl );
4415static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
4416
4418 unsigned update_hs_digest )
4419{
4420 int ret;
4421
4422 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
4423
4424 if( ssl->keep_current_message == 0 )
4425 {
4426 do {
4427
4428 ret = ssl_consume_current_message( ssl );
4429 if( ret != 0 )
4430 return( ret );
4431
4432 if( ssl_record_is_in_progress( ssl ) == 0 )
4433 {
4434#if defined(MBEDTLS_SSL_PROTO_DTLS)
4435 int have_buffered = 0;
4436
4437 /* We only check for buffered messages if the
4438 * current datagram is fully consumed. */
4440 ssl_next_record_is_in_datagram( ssl ) == 0 )
4441 {
4442 if( ssl_load_buffered_message( ssl ) == 0 )
4443 have_buffered = 1;
4444 }
4445
4446 if( have_buffered == 0 )
4447#endif /* MBEDTLS_SSL_PROTO_DTLS */
4448 {
4449 ret = ssl_get_next_record( ssl );
4451 continue;
4452
4453 if( ret != 0 )
4454 {
4455 MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
4456 return( ret );
4457 }
4458 }
4459 }
4460
4462
4463#if defined(MBEDTLS_SSL_PROTO_DTLS)
4465 {
4466 /* Buffer future message */
4467 ret = ssl_buffer_message( ssl );
4468 if( ret != 0 )
4469 return( ret );
4470
4472 }
4473#endif /* MBEDTLS_SSL_PROTO_DTLS */
4474
4475 } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ||
4477
4478 if( 0 != ret )
4479 {
4480 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
4481 return( ret );
4482 }
4483
4485 update_hs_digest == 1 )
4486 {
4488 }
4489 }
4490 else
4491 {
4492 MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
4493 ssl->keep_current_message = 0;
4494 }
4495
4496 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
4497
4498 return( 0 );
4499}
4500
4501#if defined(MBEDTLS_SSL_PROTO_DTLS)
4502static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
4503{
4504 if( ssl->in_left > ssl->next_record_offset )
4505 return( 1 );
4506
4507 return( 0 );
4508}
4509
4510static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
4511{
4512 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4513 mbedtls_ssl_hs_buffer * hs_buf;
4514 int ret = 0;
4515
4516 if( hs == NULL )
4517 return( -1 );
4518
4519 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
4520
4523 {
4524 /* Check if we have seen a ChangeCipherSpec before.
4525 * If yes, synthesize a CCS record. */
4526 if( !hs->buffering.seen_ccs )
4527 {
4528 MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
4529 ret = -1;
4530 goto exit;
4531 }
4532
4533 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
4535 ssl->in_msglen = 1;
4536 ssl->in_msg[0] = 1;
4537
4538 /* As long as they are equal, the exact value doesn't matter. */
4539 ssl->in_left = 0;
4540 ssl->next_record_offset = 0;
4541
4542 hs->buffering.seen_ccs = 0;
4543 goto exit;
4544 }
4545
4546#if defined(MBEDTLS_DEBUG_C)
4547 /* Debug only */
4548 {
4549 unsigned offset;
4551 {
4552 hs_buf = &hs->buffering.hs[offset];
4553 if( hs_buf->is_valid == 1 )
4554 {
4555 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
4556 hs->in_msg_seq + offset,
4557 hs_buf->is_complete ? "fully" : "partially" ) );
4558 }
4559 }
4560 }
4561#endif /* MBEDTLS_DEBUG_C */
4562
4563 /* Check if we have buffered and/or fully reassembled the
4564 * next handshake message. */
4565 hs_buf = &hs->buffering.hs[0];
4566 if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
4567 {
4568 /* Synthesize a record containing the buffered HS message. */
4569 size_t msg_len = ( hs_buf->data[1] << 16 ) |
4570 ( hs_buf->data[2] << 8 ) |
4571 hs_buf->data[3];
4572
4573 /* Double-check that we haven't accidentally buffered
4574 * a message that doesn't fit into the input buffer. */
4575 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
4576 {
4577 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4579 }
4580
4581 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
4582 MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
4583 hs_buf->data, msg_len + 12 );
4584
4586 ssl->in_hslen = msg_len + 12;
4587 ssl->in_msglen = msg_len + 12;
4588 memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
4589
4590 ret = 0;
4591 goto exit;
4592 }
4593 else
4594 {
4595 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
4596 hs->in_msg_seq ) );
4597 }
4598
4599 ret = -1;
4600
4601exit:
4602
4603 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
4604 return( ret );
4605}
4606
4607static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
4608 size_t desired )
4609{
4610 int offset;
4611 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4612 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
4613 (unsigned) desired ) );
4614
4615 /* Get rid of future records epoch first, if such exist. */
4616 ssl_free_buffered_record( ssl );
4617
4618 /* Check if we have enough space available now. */
4620 hs->buffering.total_bytes_buffered ) )
4621 {
4622 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
4623 return( 0 );
4624 }
4625
4626 /* We don't have enough space to buffer the next expected handshake
4627 * message. Remove buffers used for future messages to gain space,
4628 * starting with the most distant one. */
4630 offset >= 0; offset-- )
4631 {
4632 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
4633 offset ) );
4634
4635 ssl_buffering_free_slot( ssl, (uint8_t) offset );
4636
4637 /* Check if we have enough space available now. */
4639 hs->buffering.total_bytes_buffered ) )
4640 {
4641 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
4642 return( 0 );
4643 }
4644 }
4645
4646 return( -1 );
4647}
4648
4649static int ssl_buffer_message( mbedtls_ssl_context *ssl )
4650{
4651 int ret = 0;
4652 mbedtls_ssl_handshake_params * const hs = ssl->handshake;
4653
4654 if( hs == NULL )
4655 return( 0 );
4656
4657 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
4658
4659 switch( ssl->in_msgtype )
4660 {
4662 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
4663
4664 hs->buffering.seen_ccs = 1;
4665 break;
4666
4668 {
4669 unsigned recv_msg_seq_offset;
4670 unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
4671 mbedtls_ssl_hs_buffer *hs_buf;
4672 size_t msg_len = ssl->in_hslen - 12;
4673
4674 /* We should never receive an old handshake
4675 * message - double-check nonetheless. */
4676 if( recv_msg_seq < ssl->handshake->in_msg_seq )
4677 {
4678 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4680 }
4681
4682 recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
4683 if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
4684 {
4685 /* Silently ignore -- message too far in the future */
4687 ( "Ignore future HS message with sequence number %u, "
4688 "buffering window %u - %u",
4689 recv_msg_seq, ssl->handshake->in_msg_seq,
4690 ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
4691
4692 goto exit;
4693 }
4694
4695 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
4696 recv_msg_seq, recv_msg_seq_offset ) );
4697
4698 hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
4699
4700 /* Check if the buffering for this seq nr has already commenced. */
4701 if( !hs_buf->is_valid )
4702 {
4703 size_t reassembly_buf_sz;
4704
4705 hs_buf->is_fragmented =
4706 ( ssl_hs_is_proper_fragment( ssl ) == 1 );
4707
4708 /* We copy the message back into the input buffer
4709 * after reassembly, so check that it's not too large.
4710 * This is an implementation-specific limitation
4711 * and not one from the standard, hence it is not
4712 * checked in ssl_check_hs_header(). */
4713 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
4714 {
4715 /* Ignore message */
4716 goto exit;
4717 }
4718
4719 /* Check if we have enough space to buffer the message. */
4720 if( hs->buffering.total_bytes_buffered >
4722 {
4723 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4725 }
4726
4727 reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
4728 hs_buf->is_fragmented );
4729
4730 if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
4731 hs->buffering.total_bytes_buffered ) )
4732 {
4733 if( recv_msg_seq_offset > 0 )
4734 {
4735 /* If we can't buffer a future message because
4736 * of space limitations -- ignore. */
4737 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",
4738 (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4739 (unsigned) hs->buffering.total_bytes_buffered ) );
4740 goto exit;
4741 }
4742 else
4743 {
4744 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",
4745 (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
4746 (unsigned) hs->buffering.total_bytes_buffered ) );
4747 }
4748
4749 if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
4750 {
4751 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",
4752 (unsigned) msg_len,
4753 (unsigned) reassembly_buf_sz,
4755 (unsigned) hs->buffering.total_bytes_buffered ) );
4757 goto exit;
4758 }
4759 }
4760
4761 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
4762 msg_len ) );
4763
4764 hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
4765 if( hs_buf->data == NULL )
4766 {
4768 goto exit;
4769 }
4770 hs_buf->data_len = reassembly_buf_sz;
4771
4772 /* Prepare final header: copy msg_type, length and message_seq,
4773 * then add standardised fragment_offset and fragment_length */
4774 memcpy( hs_buf->data, ssl->in_msg, 6 );
4775 memset( hs_buf->data + 6, 0, 3 );
4776 memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
4777
4778 hs_buf->is_valid = 1;
4779
4780 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
4781 }
4782 else
4783 {
4784 /* Make sure msg_type and length are consistent */
4785 if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
4786 {
4787 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
4788 /* Ignore */
4789 goto exit;
4790 }
4791 }
4792
4793 if( !hs_buf->is_complete )
4794 {
4795 size_t frag_len, frag_off;
4796 unsigned char * const msg = hs_buf->data + 12;
4797
4798 /*
4799 * Check and copy current fragment
4800 */
4801
4802 /* Validation of header fields already done in
4803 * mbedtls_ssl_prepare_handshake_record(). */
4804 frag_off = ssl_get_hs_frag_off( ssl );