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