1 /* 2 * Generic SSL/TLS messaging layer functions 3 * (record layer + retransmission state machine) 4 * 5 * Copyright The Mbed TLS Contributors 6 * SPDX-License-Identifier: Apache-2.0 7 * 8 * Licensed under the Apache License, Version 2.0 (the "License"); you may 9 * not use this file except in compliance with the License. 10 * You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, software 15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 * See the License for the specific language governing permissions and 18 * limitations under the License. 19 */ 20 /* 21 * The SSL 3.0 specification was drafted by Netscape in 1996, 22 * and became an IETF standard in 1999. 23 * 24 * http://wp.netscape.com/eng/ssl3/ 25 * http://www.ietf.org/rfc/rfc2246.txt 26 * http://www.ietf.org/rfc/rfc4346.txt 27 */ 28 29 #include "common.h" 30 31 #if defined(MBEDTLS_SSL_TLS_C) 32 33 #if defined(MBEDTLS_PLATFORM_C) 34 #include "mbedtls/platform.h" 35 #else 36 #include <stdlib.h> 37 #define mbedtls_calloc calloc 38 #define mbedtls_free free 39 #endif 40 41 #include "mbedtls/ssl.h" 42 #include "mbedtls/ssl_internal.h" 43 #include "mbedtls/debug.h" 44 #include "mbedtls/error.h" 45 #include "mbedtls/platform_util.h" 46 #include "mbedtls/version.h" 47 #include "constant_time_internal.h" 48 #include "mbedtls/constant_time.h" 49 50 #include <string.h> 51 52 #if defined(MBEDTLS_USE_PSA_CRYPTO) 53 #include "mbedtls/psa_util.h" 54 #include "psa/crypto.h" 55 #endif 56 57 #if defined(MBEDTLS_X509_CRT_PARSE_C) 58 #include "mbedtls/oid.h" 59 #endif 60 61 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl ); 62 63 /* 64 * Start a timer. 65 * Passing millisecs = 0 cancels a running timer. 66 */ 67 void mbedtls_ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs ) 68 { 69 if( ssl->f_set_timer == NULL ) 70 return; 71 72 MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) ); 73 ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs ); 74 } 75 76 /* 77 * Return -1 is timer is expired, 0 if it isn't. 78 */ 79 int mbedtls_ssl_check_timer( mbedtls_ssl_context *ssl ) 80 { 81 if( ssl->f_get_timer == NULL ) 82 return( 0 ); 83 84 if( ssl->f_get_timer( ssl->p_timer ) == 2 ) 85 { 86 MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) ); 87 return( -1 ); 88 } 89 90 return( 0 ); 91 } 92 93 #if defined(MBEDTLS_SSL_RECORD_CHECKING) 94 MBEDTLS_CHECK_RETURN_CRITICAL 95 static int ssl_parse_record_header( mbedtls_ssl_context const *ssl, 96 unsigned char *buf, 97 size_t len, 98 mbedtls_record *rec ); 99 100 int mbedtls_ssl_check_record( mbedtls_ssl_context const *ssl, 101 unsigned char *buf, 102 size_t buflen ) 103 { 104 int ret = 0; 105 MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) ); 106 MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen ); 107 108 /* We don't support record checking in TLS because 109 * (a) there doesn't seem to be a usecase for it, and 110 * (b) In SSLv3 and TLS 1.0, CBC record decryption has state 111 * and we'd need to backup the transform here. 112 */ 113 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) 114 { 115 ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; 116 goto exit; 117 } 118 #if defined(MBEDTLS_SSL_PROTO_DTLS) 119 else 120 { 121 mbedtls_record rec; 122 123 ret = ssl_parse_record_header( ssl, buf, buflen, &rec ); 124 if( ret != 0 ) 125 { 126 MBEDTLS_SSL_DEBUG_RET( 3, "ssl_parse_record_header", ret ); 127 goto exit; 128 } 129 130 if( ssl->transform_in != NULL ) 131 { 132 ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, &rec ); 133 if( ret != 0 ) 134 { 135 MBEDTLS_SSL_DEBUG_RET( 3, "mbedtls_ssl_decrypt_buf", ret ); 136 goto exit; 137 } 138 } 139 } 140 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 141 142 exit: 143 /* On success, we have decrypted the buffer in-place, so make 144 * sure we don't leak any plaintext data. */ 145 mbedtls_platform_zeroize( buf, buflen ); 146 147 /* For the purpose of this API, treat messages with unexpected CID 148 * as well as such from future epochs as unexpected. */ 149 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID || 150 ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) 151 { 152 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; 153 } 154 155 MBEDTLS_SSL_DEBUG_MSG( 1, ( "<= mbedtls_ssl_check_record" ) ); 156 return( ret ); 157 } 158 #endif /* MBEDTLS_SSL_RECORD_CHECKING */ 159 160 #define SSL_DONT_FORCE_FLUSH 0 161 #define SSL_FORCE_FLUSH 1 162 163 #if defined(MBEDTLS_SSL_PROTO_DTLS) 164 165 /* Forward declarations for functions related to message buffering. */ 166 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, 167 uint8_t slot ); 168 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl ); 169 MBEDTLS_CHECK_RETURN_CRITICAL 170 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl ); 171 MBEDTLS_CHECK_RETURN_CRITICAL 172 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl ); 173 MBEDTLS_CHECK_RETURN_CRITICAL 174 static int ssl_buffer_message( mbedtls_ssl_context *ssl ); 175 MBEDTLS_CHECK_RETURN_CRITICAL 176 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl, 177 mbedtls_record const *rec ); 178 MBEDTLS_CHECK_RETURN_CRITICAL 179 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl ); 180 181 static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl ) 182 { 183 size_t mtu = mbedtls_ssl_get_current_mtu( ssl ); 184 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) 185 size_t out_buf_len = ssl->out_buf_len; 186 #else 187 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; 188 #endif 189 190 if( mtu != 0 && mtu < out_buf_len ) 191 return( mtu ); 192 193 return( out_buf_len ); 194 } 195 196 MBEDTLS_CHECK_RETURN_CRITICAL 197 static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl ) 198 { 199 size_t const bytes_written = ssl->out_left; 200 size_t const mtu = ssl_get_maximum_datagram_size( ssl ); 201 202 /* Double-check that the write-index hasn't gone 203 * past what we can transmit in a single datagram. */ 204 if( bytes_written > mtu ) 205 { 206 /* Should never happen... */ 207 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 208 } 209 210 return( (int) ( mtu - bytes_written ) ); 211 } 212 213 MBEDTLS_CHECK_RETURN_CRITICAL 214 static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl ) 215 { 216 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 217 size_t remaining, expansion; 218 size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN; 219 220 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) 221 const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl ); 222 223 if( max_len > mfl ) 224 max_len = mfl; 225 226 /* By the standard (RFC 6066 Sect. 4), the MFL extension 227 * only limits the maximum record payload size, so in theory 228 * we would be allowed to pack multiple records of payload size 229 * MFL into a single datagram. However, this would mean that there's 230 * no way to explicitly communicate MTU restrictions to the peer. 231 * 232 * The following reduction of max_len makes sure that we never 233 * write datagrams larger than MFL + Record Expansion Overhead. 234 */ 235 if( max_len <= ssl->out_left ) 236 return( 0 ); 237 238 max_len -= ssl->out_left; 239 #endif 240 241 ret = ssl_get_remaining_space_in_datagram( ssl ); 242 if( ret < 0 ) 243 return( ret ); 244 remaining = (size_t) ret; 245 246 ret = mbedtls_ssl_get_record_expansion( ssl ); 247 if( ret < 0 ) 248 return( ret ); 249 expansion = (size_t) ret; 250 251 if( remaining <= expansion ) 252 return( 0 ); 253 254 remaining -= expansion; 255 if( remaining >= max_len ) 256 remaining = max_len; 257 258 return( (int) remaining ); 259 } 260 261 /* 262 * Double the retransmit timeout value, within the allowed range, 263 * returning -1 if the maximum value has already been reached. 264 */ 265 MBEDTLS_CHECK_RETURN_CRITICAL 266 static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl ) 267 { 268 uint32_t new_timeout; 269 270 if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max ) 271 return( -1 ); 272 273 /* Implement the final paragraph of RFC 6347 section 4.1.1.1 274 * in the following way: after the initial transmission and a first 275 * retransmission, back off to a temporary estimated MTU of 508 bytes. 276 * This value is guaranteed to be deliverable (if not guaranteed to be 277 * delivered) of any compliant IPv4 (and IPv6) network, and should work 278 * on most non-IP stacks too. */ 279 if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min ) 280 { 281 ssl->handshake->mtu = 508; 282 MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) ); 283 } 284 285 new_timeout = 2 * ssl->handshake->retransmit_timeout; 286 287 /* Avoid arithmetic overflow and range overflow */ 288 if( new_timeout < ssl->handshake->retransmit_timeout || 289 new_timeout > ssl->conf->hs_timeout_max ) 290 { 291 new_timeout = ssl->conf->hs_timeout_max; 292 } 293 294 ssl->handshake->retransmit_timeout = new_timeout; 295 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %lu millisecs", 296 (unsigned long) ssl->handshake->retransmit_timeout ) ); 297 298 return( 0 ); 299 } 300 301 static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl ) 302 { 303 ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min; 304 MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %lu millisecs", 305 (unsigned long) ssl->handshake->retransmit_timeout ) ); 306 } 307 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 308 309 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) 310 int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl, 311 const unsigned char *key_enc, const unsigned char *key_dec, 312 size_t keylen, 313 const unsigned char *iv_enc, const unsigned char *iv_dec, 314 size_t ivlen, 315 const unsigned char *mac_enc, const unsigned char *mac_dec, 316 size_t maclen ) = NULL; 317 int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL; 318 int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL; 319 int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL; 320 int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL; 321 int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL; 322 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ 323 324 /* 325 * Encryption/decryption functions 326 */ 327 328 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || \ 329 defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) 330 331 static size_t ssl_compute_padding_length( size_t len, 332 size_t granularity ) 333 { 334 return( ( granularity - ( len + 1 ) % granularity ) % granularity ); 335 } 336 337 /* This functions transforms a (D)TLS plaintext fragment and a record content 338 * type into an instance of the (D)TLSInnerPlaintext structure. This is used 339 * in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect 340 * a record's content type. 341 * 342 * struct { 343 * opaque content[DTLSPlaintext.length]; 344 * ContentType real_type; 345 * uint8 zeros[length_of_padding]; 346 * } (D)TLSInnerPlaintext; 347 * 348 * Input: 349 * - `content`: The beginning of the buffer holding the 350 * plaintext to be wrapped. 351 * - `*content_size`: The length of the plaintext in Bytes. 352 * - `max_len`: The number of Bytes available starting from 353 * `content`. This must be `>= *content_size`. 354 * - `rec_type`: The desired record content type. 355 * 356 * Output: 357 * - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure. 358 * - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure. 359 * 360 * Returns: 361 * - `0` on success. 362 * - A negative error code if `max_len` didn't offer enough space 363 * for the expansion. 364 */ 365 MBEDTLS_CHECK_RETURN_CRITICAL 366 static int ssl_build_inner_plaintext( unsigned char *content, 367 size_t *content_size, 368 size_t remaining, 369 uint8_t rec_type, 370 size_t pad ) 371 { 372 size_t len = *content_size; 373 374 /* Write real content type */ 375 if( remaining == 0 ) 376 return( -1 ); 377 content[ len ] = rec_type; 378 len++; 379 remaining--; 380 381 if( remaining < pad ) 382 return( -1 ); 383 memset( content + len, 0, pad ); 384 len += pad; 385 remaining -= pad; 386 387 *content_size = len; 388 return( 0 ); 389 } 390 391 /* This function parses a (D)TLSInnerPlaintext structure. 392 * See ssl_build_inner_plaintext() for details. */ 393 MBEDTLS_CHECK_RETURN_CRITICAL 394 static int ssl_parse_inner_plaintext( unsigned char const *content, 395 size_t *content_size, 396 uint8_t *rec_type ) 397 { 398 size_t remaining = *content_size; 399 400 /* Determine length of padding by skipping zeroes from the back. */ 401 do 402 { 403 if( remaining == 0 ) 404 return( -1 ); 405 remaining--; 406 } while( content[ remaining ] == 0 ); 407 408 *content_size = remaining; 409 *rec_type = content[ remaining ]; 410 411 return( 0 ); 412 } 413 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID || 414 MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ 415 416 /* `add_data` must have size 13 Bytes if the CID extension is disabled, 417 * and 13 + 1 + CID-length Bytes if the CID extension is enabled. */ 418 static void ssl_extract_add_data_from_record( unsigned char* add_data, 419 size_t *add_data_len, 420 mbedtls_record *rec, 421 unsigned minor_ver ) 422 { 423 /* Quoting RFC 5246 (TLS 1.2): 424 * 425 * additional_data = seq_num + TLSCompressed.type + 426 * TLSCompressed.version + TLSCompressed.length; 427 * 428 * For the CID extension, this is extended as follows 429 * (quoting draft-ietf-tls-dtls-connection-id-05, 430 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05): 431 * 432 * additional_data = seq_num + DTLSPlaintext.type + 433 * DTLSPlaintext.version + 434 * cid + 435 * cid_length + 436 * length_of_DTLSInnerPlaintext; 437 * 438 * For TLS 1.3, the record sequence number is dropped from the AAD 439 * and encoded within the nonce of the AEAD operation instead. 440 */ 441 442 unsigned char *cur = add_data; 443 444 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) 445 if( minor_ver != MBEDTLS_SSL_MINOR_VERSION_4 ) 446 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ 447 { 448 ((void) minor_ver); 449 memcpy( cur, rec->ctr, sizeof( rec->ctr ) ); 450 cur += sizeof( rec->ctr ); 451 } 452 453 *cur = rec->type; 454 cur++; 455 456 memcpy( cur, rec->ver, sizeof( rec->ver ) ); 457 cur += sizeof( rec->ver ); 458 459 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 460 if( rec->cid_len != 0 ) 461 { 462 memcpy( cur, rec->cid, rec->cid_len ); 463 cur += rec->cid_len; 464 465 *cur = rec->cid_len; 466 cur++; 467 468 MBEDTLS_PUT_UINT16_BE( rec->data_len, cur, 0 ); 469 cur += 2; 470 } 471 else 472 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 473 { 474 MBEDTLS_PUT_UINT16_BE( rec->data_len, cur, 0 ); 475 cur += 2; 476 } 477 478 *add_data_len = cur - add_data; 479 } 480 481 #if defined(MBEDTLS_SSL_PROTO_SSL3) 482 483 #define SSL3_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */ 484 485 /* 486 * SSLv3.0 MAC functions 487 */ 488 MBEDTLS_CHECK_RETURN_CRITICAL 489 static int ssl_mac( mbedtls_md_context_t *md_ctx, 490 const unsigned char *secret, 491 const unsigned char *buf, size_t len, 492 const unsigned char *ctr, int type, 493 unsigned char out[SSL3_MAC_MAX_BYTES] ) 494 { 495 unsigned char header[11]; 496 unsigned char padding[48]; 497 int padlen; 498 int md_size = mbedtls_md_get_size( md_ctx->md_info ); 499 int md_type = mbedtls_md_get_type( md_ctx->md_info ); 500 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 501 502 /* Only MD5 and SHA-1 supported */ 503 if( md_type == MBEDTLS_MD_MD5 ) 504 padlen = 48; 505 else 506 padlen = 40; 507 508 memcpy( header, ctr, 8 ); 509 header[8] = (unsigned char) type; 510 MBEDTLS_PUT_UINT16_BE( len, header, 9); 511 512 memset( padding, 0x36, padlen ); 513 ret = mbedtls_md_starts( md_ctx ); 514 if( ret != 0 ) 515 return( ret ); 516 ret = mbedtls_md_update( md_ctx, secret, md_size ); 517 if( ret != 0 ) 518 return( ret ); 519 ret = mbedtls_md_update( md_ctx, padding, padlen ); 520 if( ret != 0 ) 521 return( ret ); 522 ret = mbedtls_md_update( md_ctx, header, 11 ); 523 if( ret != 0 ) 524 return( ret ); 525 ret = mbedtls_md_update( md_ctx, buf, len ); 526 if( ret != 0 ) 527 return( ret ); 528 ret = mbedtls_md_finish( md_ctx, out ); 529 if( ret != 0 ) 530 return( ret ); 531 532 memset( padding, 0x5C, padlen ); 533 ret = mbedtls_md_starts( md_ctx ); 534 if( ret != 0 ) 535 return( ret ); 536 ret = mbedtls_md_update( md_ctx, secret, md_size ); 537 if( ret != 0 ) 538 return( ret ); 539 ret = mbedtls_md_update( md_ctx, padding, padlen ); 540 if( ret != 0 ) 541 return( ret ); 542 ret = mbedtls_md_update( md_ctx, out, md_size ); 543 if( ret != 0 ) 544 return( ret ); 545 ret = mbedtls_md_finish( md_ctx, out ); 546 if( ret != 0 ) 547 return( ret ); 548 549 return( 0 ); 550 } 551 #endif /* MBEDTLS_SSL_PROTO_SSL3 */ 552 553 #if defined(MBEDTLS_GCM_C) || \ 554 defined(MBEDTLS_CCM_C) || \ 555 defined(MBEDTLS_CHACHAPOLY_C) 556 MBEDTLS_CHECK_RETURN_CRITICAL 557 static int ssl_transform_aead_dynamic_iv_is_explicit( 558 mbedtls_ssl_transform const *transform ) 559 { 560 return( transform->ivlen != transform->fixed_ivlen ); 561 } 562 563 /* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV ) 564 * 565 * Concretely, this occurs in two variants: 566 * 567 * a) Fixed and dynamic IV lengths add up to total IV length, giving 568 * IV = fixed_iv || dynamic_iv 569 * 570 * This variant is used in TLS 1.2 when used with GCM or CCM. 571 * 572 * b) Fixed IV lengths matches total IV length, giving 573 * IV = fixed_iv XOR ( 0 || dynamic_iv ) 574 * 575 * This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly. 576 * 577 * See also the documentation of mbedtls_ssl_transform. 578 * 579 * This function has the precondition that 580 * 581 * dst_iv_len >= max( fixed_iv_len, dynamic_iv_len ) 582 * 583 * which has to be ensured by the caller. If this precondition 584 * violated, the behavior of this function is undefined. 585 */ 586 static void ssl_build_record_nonce( unsigned char *dst_iv, 587 size_t dst_iv_len, 588 unsigned char const *fixed_iv, 589 size_t fixed_iv_len, 590 unsigned char const *dynamic_iv, 591 size_t dynamic_iv_len ) 592 { 593 size_t i; 594 595 /* Start with Fixed IV || 0 */ 596 memset( dst_iv, 0, dst_iv_len ); 597 memcpy( dst_iv, fixed_iv, fixed_iv_len ); 598 599 dst_iv += dst_iv_len - dynamic_iv_len; 600 for( i = 0; i < dynamic_iv_len; i++ ) 601 dst_iv[i] ^= dynamic_iv[i]; 602 } 603 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ 604 605 int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl, 606 mbedtls_ssl_transform *transform, 607 mbedtls_record *rec, 608 int (*f_rng)(void *, unsigned char *, size_t), 609 void *p_rng ) 610 { 611 mbedtls_cipher_mode_t mode; 612 int auth_done = 0; 613 unsigned char * data; 614 unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_OUT_LEN_MAX ]; 615 size_t add_data_len; 616 size_t post_avail; 617 618 /* The SSL context is only used for debugging purposes! */ 619 #if !defined(MBEDTLS_DEBUG_C) 620 ssl = NULL; /* make sure we don't use it except for debug */ 621 ((void) ssl); 622 #endif 623 624 /* The PRNG is used for dynamic IV generation that's used 625 * for CBC transformations in TLS 1.1 and TLS 1.2. */ 626 #if !( defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \ 627 ( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) ) 628 ((void) f_rng); 629 ((void) p_rng); 630 #endif 631 632 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) ); 633 634 if( transform == NULL ) 635 { 636 MBEDTLS_SSL_DEBUG_MSG( 1, ( "no transform provided to encrypt_buf" ) ); 637 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 638 } 639 if( rec == NULL 640 || rec->buf == NULL 641 || rec->buf_len < rec->data_offset 642 || rec->buf_len - rec->data_offset < rec->data_len 643 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 644 || rec->cid_len != 0 645 #endif 646 ) 647 { 648 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to encrypt_buf" ) ); 649 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 650 } 651 652 data = rec->buf + rec->data_offset; 653 post_avail = rec->buf_len - ( rec->data_len + rec->data_offset ); 654 MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload", 655 data, rec->data_len ); 656 657 mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ); 658 659 if( rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN ) 660 { 661 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record content %" MBEDTLS_PRINTF_SIZET 662 " too large, maximum %" MBEDTLS_PRINTF_SIZET, 663 rec->data_len, 664 (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN ) ); 665 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 666 } 667 668 /* The following two code paths implement the (D)TLSInnerPlaintext 669 * structure present in TLS 1.3 and DTLS 1.2 + CID. 670 * 671 * See ssl_build_inner_plaintext() for more information. 672 * 673 * Note that this changes `rec->data_len`, and hence 674 * `post_avail` needs to be recalculated afterwards. 675 * 676 * Note also that the two code paths cannot occur simultaneously 677 * since they apply to different versions of the protocol. There 678 * is hence no risk of double-addition of the inner plaintext. 679 */ 680 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) 681 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) 682 { 683 size_t padding = 684 ssl_compute_padding_length( rec->data_len, 685 MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY ); 686 if( ssl_build_inner_plaintext( data, 687 &rec->data_len, 688 post_avail, 689 rec->type, 690 padding ) != 0 ) 691 { 692 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 693 } 694 695 rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA; 696 } 697 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ 698 699 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 700 /* 701 * Add CID information 702 */ 703 rec->cid_len = transform->out_cid_len; 704 memcpy( rec->cid, transform->out_cid, transform->out_cid_len ); 705 MBEDTLS_SSL_DEBUG_BUF( 3, "CID", rec->cid, rec->cid_len ); 706 707 if( rec->cid_len != 0 ) 708 { 709 size_t padding = 710 ssl_compute_padding_length( rec->data_len, 711 MBEDTLS_SSL_CID_PADDING_GRANULARITY ); 712 /* 713 * Wrap plaintext into DTLSInnerPlaintext structure. 714 * See ssl_build_inner_plaintext() for more information. 715 * 716 * Note that this changes `rec->data_len`, and hence 717 * `post_avail` needs to be recalculated afterwards. 718 */ 719 if( ssl_build_inner_plaintext( data, 720 &rec->data_len, 721 post_avail, 722 rec->type, 723 padding ) != 0 ) 724 { 725 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 726 } 727 728 rec->type = MBEDTLS_SSL_MSG_CID; 729 } 730 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 731 732 post_avail = rec->buf_len - ( rec->data_len + rec->data_offset ); 733 734 /* 735 * Add MAC before if needed 736 */ 737 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) 738 if( mode == MBEDTLS_MODE_STREAM || 739 ( mode == MBEDTLS_MODE_CBC 740 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) 741 && transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED 742 #endif 743 ) ) 744 { 745 if( post_avail < transform->maclen ) 746 { 747 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); 748 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 749 } 750 751 #if defined(MBEDTLS_SSL_PROTO_SSL3) 752 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) 753 { 754 unsigned char mac[SSL3_MAC_MAX_BYTES]; 755 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 756 ret = ssl_mac( &transform->md_ctx_enc, transform->mac_enc, 757 data, rec->data_len, rec->ctr, rec->type, mac ); 758 if( ret == 0 ) 759 memcpy( data + rec->data_len, mac, transform->maclen ); 760 mbedtls_platform_zeroize( mac, transform->maclen ); 761 if( ret != 0 ) 762 { 763 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_mac", ret ); 764 return( ret ); 765 } 766 } 767 else 768 #endif 769 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ 770 defined(MBEDTLS_SSL_PROTO_TLS1_2) 771 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) 772 { 773 unsigned char mac[MBEDTLS_SSL_MAC_ADD]; 774 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 775 776 ssl_extract_add_data_from_record( add_data, &add_data_len, rec, 777 transform->minor_ver ); 778 779 ret = mbedtls_md_hmac_update( &transform->md_ctx_enc, 780 add_data, add_data_len ); 781 if( ret != 0 ) 782 goto hmac_failed_etm_disabled; 783 ret = mbedtls_md_hmac_update( &transform->md_ctx_enc, 784 data, rec->data_len ); 785 if( ret != 0 ) 786 goto hmac_failed_etm_disabled; 787 ret = mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac ); 788 if( ret != 0 ) 789 goto hmac_failed_etm_disabled; 790 ret = mbedtls_md_hmac_reset( &transform->md_ctx_enc ); 791 if( ret != 0 ) 792 goto hmac_failed_etm_disabled; 793 794 memcpy( data + rec->data_len, mac, transform->maclen ); 795 796 hmac_failed_etm_disabled: 797 mbedtls_platform_zeroize( mac, transform->maclen ); 798 if( ret != 0 ) 799 { 800 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_hmac_xxx", ret ); 801 return( ret ); 802 } 803 } 804 else 805 #endif 806 { 807 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 808 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 809 } 810 811 MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", data + rec->data_len, 812 transform->maclen ); 813 814 rec->data_len += transform->maclen; 815 post_avail -= transform->maclen; 816 auth_done++; 817 } 818 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ 819 820 /* 821 * Encrypt 822 */ 823 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) 824 if( mode == MBEDTLS_MODE_STREAM ) 825 { 826 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 827 size_t olen; 828 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", " 829 "including %d bytes of padding", 830 rec->data_len, 0 ) ); 831 832 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc, 833 transform->iv_enc, transform->ivlen, 834 data, rec->data_len, 835 data, &olen ) ) != 0 ) 836 { 837 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); 838 return( ret ); 839 } 840 841 if( rec->data_len != olen ) 842 { 843 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 844 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 845 } 846 } 847 else 848 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ 849 850 #if defined(MBEDTLS_GCM_C) || \ 851 defined(MBEDTLS_CCM_C) || \ 852 defined(MBEDTLS_CHACHAPOLY_C) 853 if( mode == MBEDTLS_MODE_GCM || 854 mode == MBEDTLS_MODE_CCM || 855 mode == MBEDTLS_MODE_CHACHAPOLY ) 856 { 857 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 858 unsigned char iv[12]; 859 unsigned char *dynamic_iv; 860 size_t dynamic_iv_len; 861 int dynamic_iv_is_explicit = 862 ssl_transform_aead_dynamic_iv_is_explicit( transform ); 863 864 /* Check that there's space for the authentication tag. */ 865 if( post_avail < transform->taglen ) 866 { 867 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); 868 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 869 } 870 871 /* 872 * Build nonce for AEAD encryption. 873 * 874 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic 875 * part of the IV is prepended to the ciphertext and 876 * can be chosen freely - in particular, it need not 877 * agree with the record sequence number. 878 * However, since ChaChaPoly as well as all AEAD modes 879 * in TLS 1.3 use the record sequence number as the 880 * dynamic part of the nonce, we uniformly use the 881 * record sequence number here in all cases. 882 */ 883 dynamic_iv = rec->ctr; 884 dynamic_iv_len = sizeof( rec->ctr ); 885 886 ssl_build_record_nonce( iv, sizeof( iv ), 887 transform->iv_enc, 888 transform->fixed_ivlen, 889 dynamic_iv, 890 dynamic_iv_len ); 891 892 /* 893 * Build additional data for AEAD encryption. 894 * This depends on the TLS version. 895 */ 896 ssl_extract_add_data_from_record( add_data, &add_data_len, rec, 897 transform->minor_ver ); 898 899 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)", 900 iv, transform->ivlen ); 901 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)", 902 dynamic_iv, 903 dynamic_iv_is_explicit ? dynamic_iv_len : 0 ); 904 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", 905 add_data, add_data_len ); 906 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", " 907 "including 0 bytes of padding", 908 rec->data_len ) ); 909 910 /* 911 * Encrypt and authenticate 912 */ 913 914 if( ( ret = mbedtls_cipher_auth_encrypt_ext( &transform->cipher_ctx_enc, 915 iv, transform->ivlen, 916 add_data, add_data_len, 917 data, rec->data_len, /* src */ 918 data, rec->buf_len - (data - rec->buf), /* dst */ 919 &rec->data_len, 920 transform->taglen ) ) != 0 ) 921 { 922 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret ); 923 return( ret ); 924 } 925 MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", 926 data + rec->data_len - transform->taglen, 927 transform->taglen ); 928 /* Account for authentication tag. */ 929 post_avail -= transform->taglen; 930 931 /* 932 * Prefix record content with dynamic IV in case it is explicit. 933 */ 934 if( dynamic_iv_is_explicit != 0 ) 935 { 936 if( rec->data_offset < dynamic_iv_len ) 937 { 938 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); 939 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 940 } 941 942 memcpy( data - dynamic_iv_len, dynamic_iv, dynamic_iv_len ); 943 rec->data_offset -= dynamic_iv_len; 944 rec->data_len += dynamic_iv_len; 945 } 946 947 auth_done++; 948 } 949 else 950 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */ 951 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) 952 if( mode == MBEDTLS_MODE_CBC ) 953 { 954 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 955 size_t padlen, i; 956 size_t olen; 957 958 /* Currently we're always using minimal padding 959 * (up to 255 bytes would be allowed). */ 960 padlen = transform->ivlen - ( rec->data_len + 1 ) % transform->ivlen; 961 if( padlen == transform->ivlen ) 962 padlen = 0; 963 964 /* Check there's enough space in the buffer for the padding. */ 965 if( post_avail < padlen + 1 ) 966 { 967 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); 968 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 969 } 970 971 for( i = 0; i <= padlen; i++ ) 972 data[rec->data_len + i] = (unsigned char) padlen; 973 974 rec->data_len += padlen + 1; 975 post_avail -= padlen + 1; 976 977 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) 978 /* 979 * Prepend per-record IV for block cipher in TLS v1.1 and up as per 980 * Method 1 (6.2.3.2. in RFC4346 and RFC5246) 981 */ 982 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) 983 { 984 if( f_rng == NULL ) 985 { 986 MBEDTLS_SSL_DEBUG_MSG( 1, ( "No PRNG provided to encrypt_record routine" ) ); 987 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 988 } 989 990 if( rec->data_offset < transform->ivlen ) 991 { 992 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); 993 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 994 } 995 996 /* 997 * Generate IV 998 */ 999 ret = f_rng( p_rng, transform->iv_enc, transform->ivlen ); 1000 if( ret != 0 ) 1001 return( ret ); 1002 1003 memcpy( data - transform->ivlen, transform->iv_enc, 1004 transform->ivlen ); 1005 1006 } 1007 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ 1008 1009 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %" MBEDTLS_PRINTF_SIZET ", " 1010 "including %" MBEDTLS_PRINTF_SIZET 1011 " bytes of IV and %" MBEDTLS_PRINTF_SIZET " bytes of padding", 1012 rec->data_len, transform->ivlen, 1013 padlen + 1 ) ); 1014 1015 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc, 1016 transform->iv_enc, 1017 transform->ivlen, 1018 data, rec->data_len, 1019 data, &olen ) ) != 0 ) 1020 { 1021 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); 1022 return( ret ); 1023 } 1024 1025 if( rec->data_len != olen ) 1026 { 1027 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1028 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1029 } 1030 1031 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) 1032 if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) 1033 { 1034 /* 1035 * Save IV in SSL3 and TLS1 1036 */ 1037 memcpy( transform->iv_enc, transform->cipher_ctx_enc.iv, 1038 transform->ivlen ); 1039 } 1040 else 1041 #endif 1042 { 1043 data -= transform->ivlen; 1044 rec->data_offset -= transform->ivlen; 1045 rec->data_len += transform->ivlen; 1046 } 1047 1048 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) 1049 if( auth_done == 0 ) 1050 { 1051 unsigned char mac[MBEDTLS_SSL_MAC_ADD]; 1052 1053 /* 1054 * MAC(MAC_write_key, seq_num + 1055 * TLSCipherText.type + 1056 * TLSCipherText.version + 1057 * length_of( (IV +) ENC(...) ) + 1058 * IV + // except for TLS 1.0 1059 * ENC(content + padding + padding_length)); 1060 */ 1061 1062 if( post_avail < transform->maclen) 1063 { 1064 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) ); 1065 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 1066 } 1067 1068 ssl_extract_add_data_from_record( add_data, &add_data_len, 1069 rec, transform->minor_ver ); 1070 1071 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); 1072 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, 1073 add_data_len ); 1074 1075 ret = mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data, 1076 add_data_len ); 1077 if( ret != 0 ) 1078 goto hmac_failed_etm_enabled; 1079 ret = mbedtls_md_hmac_update( &transform->md_ctx_enc, 1080 data, rec->data_len ); 1081 if( ret != 0 ) 1082 goto hmac_failed_etm_enabled; 1083 ret = mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac ); 1084 if( ret != 0 ) 1085 goto hmac_failed_etm_enabled; 1086 ret = mbedtls_md_hmac_reset( &transform->md_ctx_enc ); 1087 if( ret != 0 ) 1088 goto hmac_failed_etm_enabled; 1089 1090 memcpy( data + rec->data_len, mac, transform->maclen ); 1091 1092 rec->data_len += transform->maclen; 1093 post_avail -= transform->maclen; 1094 auth_done++; 1095 1096 hmac_failed_etm_enabled: 1097 mbedtls_platform_zeroize( mac, transform->maclen ); 1098 if( ret != 0 ) 1099 { 1100 MBEDTLS_SSL_DEBUG_RET( 1, "HMAC calculation failed", ret ); 1101 return( ret ); 1102 } 1103 } 1104 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ 1105 } 1106 else 1107 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC) */ 1108 { 1109 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1110 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1111 } 1112 1113 /* Make extra sure authentication was performed, exactly once */ 1114 if( auth_done != 1 ) 1115 { 1116 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1117 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1118 } 1119 1120 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) ); 1121 1122 return( 0 ); 1123 } 1124 1125 int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl, 1126 mbedtls_ssl_transform *transform, 1127 mbedtls_record *rec ) 1128 { 1129 size_t olen; 1130 mbedtls_cipher_mode_t mode; 1131 int ret, auth_done = 0; 1132 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) 1133 size_t padlen = 0, correct = 1; 1134 #endif 1135 unsigned char* data; 1136 unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_IN_LEN_MAX ]; 1137 size_t add_data_len; 1138 1139 #if !defined(MBEDTLS_DEBUG_C) 1140 ssl = NULL; /* make sure we don't use it except for debug */ 1141 ((void) ssl); 1142 #endif 1143 1144 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) ); 1145 if( rec == NULL || 1146 rec->buf == NULL || 1147 rec->buf_len < rec->data_offset || 1148 rec->buf_len - rec->data_offset < rec->data_len ) 1149 { 1150 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to decrypt_buf" ) ); 1151 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1152 } 1153 1154 data = rec->buf + rec->data_offset; 1155 mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_dec ); 1156 1157 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 1158 /* 1159 * Match record's CID with incoming CID. 1160 */ 1161 if( rec->cid_len != transform->in_cid_len || 1162 memcmp( rec->cid, transform->in_cid, rec->cid_len ) != 0 ) 1163 { 1164 return( MBEDTLS_ERR_SSL_UNEXPECTED_CID ); 1165 } 1166 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 1167 1168 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) 1169 if( mode == MBEDTLS_MODE_STREAM ) 1170 { 1171 padlen = 0; 1172 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec, 1173 transform->iv_dec, 1174 transform->ivlen, 1175 data, rec->data_len, 1176 data, &olen ) ) != 0 ) 1177 { 1178 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); 1179 return( ret ); 1180 } 1181 1182 if( rec->data_len != olen ) 1183 { 1184 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1185 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1186 } 1187 } 1188 else 1189 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ 1190 #if defined(MBEDTLS_GCM_C) || \ 1191 defined(MBEDTLS_CCM_C) || \ 1192 defined(MBEDTLS_CHACHAPOLY_C) 1193 if( mode == MBEDTLS_MODE_GCM || 1194 mode == MBEDTLS_MODE_CCM || 1195 mode == MBEDTLS_MODE_CHACHAPOLY ) 1196 { 1197 unsigned char iv[12]; 1198 unsigned char *dynamic_iv; 1199 size_t dynamic_iv_len; 1200 1201 /* 1202 * Extract dynamic part of nonce for AEAD decryption. 1203 * 1204 * Note: In the case of CCM and GCM in TLS 1.2, the dynamic 1205 * part of the IV is prepended to the ciphertext and 1206 * can be chosen freely - in particular, it need not 1207 * agree with the record sequence number. 1208 */ 1209 dynamic_iv_len = sizeof( rec->ctr ); 1210 if( ssl_transform_aead_dynamic_iv_is_explicit( transform ) == 1 ) 1211 { 1212 if( rec->data_len < dynamic_iv_len ) 1213 { 1214 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET 1215 " ) < explicit_iv_len (%" MBEDTLS_PRINTF_SIZET ") ", 1216 rec->data_len, 1217 dynamic_iv_len ) ); 1218 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 1219 } 1220 dynamic_iv = data; 1221 1222 data += dynamic_iv_len; 1223 rec->data_offset += dynamic_iv_len; 1224 rec->data_len -= dynamic_iv_len; 1225 } 1226 else 1227 { 1228 dynamic_iv = rec->ctr; 1229 } 1230 1231 /* Check that there's space for the authentication tag. */ 1232 if( rec->data_len < transform->taglen ) 1233 { 1234 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET 1235 ") < taglen (%" MBEDTLS_PRINTF_SIZET ") ", 1236 rec->data_len, 1237 transform->taglen ) ); 1238 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 1239 } 1240 rec->data_len -= transform->taglen; 1241 1242 /* 1243 * Prepare nonce from dynamic and static parts. 1244 */ 1245 ssl_build_record_nonce( iv, sizeof( iv ), 1246 transform->iv_dec, 1247 transform->fixed_ivlen, 1248 dynamic_iv, 1249 dynamic_iv_len ); 1250 1251 /* 1252 * Build additional data for AEAD encryption. 1253 * This depends on the TLS version. 1254 */ 1255 ssl_extract_add_data_from_record( add_data, &add_data_len, rec, 1256 transform->minor_ver ); 1257 MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", 1258 add_data, add_data_len ); 1259 1260 /* Because of the check above, we know that there are 1261 * explicit_iv_len Bytes preceding data, and taglen 1262 * bytes following data + data_len. This justifies 1263 * the debug message and the invocation of 1264 * mbedtls_cipher_auth_decrypt() below. */ 1265 1266 MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen ); 1267 MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", data + rec->data_len, 1268 transform->taglen ); 1269 1270 /* 1271 * Decrypt and authenticate 1272 */ 1273 if( ( ret = mbedtls_cipher_auth_decrypt_ext( &transform->cipher_ctx_dec, 1274 iv, transform->ivlen, 1275 add_data, add_data_len, 1276 data, rec->data_len + transform->taglen, /* src */ 1277 data, rec->buf_len - (data - rec->buf), &olen, /* dst */ 1278 transform->taglen ) ) != 0 ) 1279 { 1280 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret ); 1281 1282 if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) 1283 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 1284 1285 return( ret ); 1286 } 1287 auth_done++; 1288 1289 /* Double-check that AEAD decryption doesn't change content length. */ 1290 if( olen != rec->data_len ) 1291 { 1292 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1293 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1294 } 1295 } 1296 else 1297 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ 1298 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) 1299 if( mode == MBEDTLS_MODE_CBC ) 1300 { 1301 size_t minlen = 0; 1302 1303 /* 1304 * Check immediate ciphertext sanity 1305 */ 1306 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) 1307 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) 1308 { 1309 /* The ciphertext is prefixed with the CBC IV. */ 1310 minlen += transform->ivlen; 1311 } 1312 #endif 1313 1314 /* Size considerations: 1315 * 1316 * - The CBC cipher text must not be empty and hence 1317 * at least of size transform->ivlen. 1318 * 1319 * Together with the potential IV-prefix, this explains 1320 * the first of the two checks below. 1321 * 1322 * - The record must contain a MAC, either in plain or 1323 * encrypted, depending on whether Encrypt-then-MAC 1324 * is used or not. 1325 * - If it is, the message contains the IV-prefix, 1326 * the CBC ciphertext, and the MAC. 1327 * - If it is not, the padded plaintext, and hence 1328 * the CBC ciphertext, has at least length maclen + 1 1329 * because there is at least the padding length byte. 1330 * 1331 * As the CBC ciphertext is not empty, both cases give the 1332 * lower bound minlen + maclen + 1 on the record size, which 1333 * we test for in the second check below. 1334 */ 1335 if( rec->data_len < minlen + transform->ivlen || 1336 rec->data_len < minlen + transform->maclen + 1 ) 1337 { 1338 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET 1339 ") < max( ivlen(%" MBEDTLS_PRINTF_SIZET 1340 "), maclen (%" MBEDTLS_PRINTF_SIZET ") " 1341 "+ 1 ) ( + expl IV )", rec->data_len, 1342 transform->ivlen, 1343 transform->maclen ) ); 1344 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 1345 } 1346 1347 /* 1348 * Authenticate before decrypt if enabled 1349 */ 1350 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) 1351 if( transform->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) 1352 { 1353 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD]; 1354 1355 MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); 1356 1357 /* Update data_len in tandem with add_data. 1358 * 1359 * The subtraction is safe because of the previous check 1360 * data_len >= minlen + maclen + 1. 1361 * 1362 * Afterwards, we know that data + data_len is followed by at 1363 * least maclen Bytes, which justifies the call to 1364 * mbedtls_ct_memcmp() below. 1365 * 1366 * Further, we still know that data_len > minlen */ 1367 rec->data_len -= transform->maclen; 1368 ssl_extract_add_data_from_record( add_data, &add_data_len, rec, 1369 transform->minor_ver ); 1370 1371 /* Calculate expected MAC. */ 1372 MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data, 1373 add_data_len ); 1374 ret = mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data, 1375 add_data_len ); 1376 if( ret != 0 ) 1377 goto hmac_failed_etm_enabled; 1378 ret = mbedtls_md_hmac_update( &transform->md_ctx_dec, 1379 data, rec->data_len ); 1380 if( ret != 0 ) 1381 goto hmac_failed_etm_enabled; 1382 ret = mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect ); 1383 if( ret != 0 ) 1384 goto hmac_failed_etm_enabled; 1385 ret = mbedtls_md_hmac_reset( &transform->md_ctx_dec ); 1386 if( ret != 0 ) 1387 goto hmac_failed_etm_enabled; 1388 1389 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", data + rec->data_len, 1390 transform->maclen ); 1391 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, 1392 transform->maclen ); 1393 1394 /* Compare expected MAC with MAC at the end of the record. */ 1395 if( mbedtls_ct_memcmp( data + rec->data_len, mac_expect, 1396 transform->maclen ) != 0 ) 1397 { 1398 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); 1399 ret = MBEDTLS_ERR_SSL_INVALID_MAC; 1400 goto hmac_failed_etm_enabled; 1401 } 1402 auth_done++; 1403 1404 hmac_failed_etm_enabled: 1405 mbedtls_platform_zeroize( mac_expect, transform->maclen ); 1406 if( ret != 0 ) 1407 { 1408 if( ret != MBEDTLS_ERR_SSL_INVALID_MAC ) 1409 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_hmac_xxx", ret ); 1410 return( ret ); 1411 } 1412 } 1413 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ 1414 1415 /* 1416 * Check length sanity 1417 */ 1418 1419 /* We know from above that data_len > minlen >= 0, 1420 * so the following check in particular implies that 1421 * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */ 1422 if( rec->data_len % transform->ivlen != 0 ) 1423 { 1424 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET 1425 ") %% ivlen (%" MBEDTLS_PRINTF_SIZET ") != 0", 1426 rec->data_len, transform->ivlen ) ); 1427 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 1428 } 1429 1430 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) 1431 /* 1432 * Initialize for prepended IV for block cipher in TLS v1.1 and up 1433 */ 1434 if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) 1435 { 1436 /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */ 1437 memcpy( transform->iv_dec, data, transform->ivlen ); 1438 1439 data += transform->ivlen; 1440 rec->data_offset += transform->ivlen; 1441 rec->data_len -= transform->ivlen; 1442 } 1443 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ 1444 1445 /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */ 1446 1447 if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec, 1448 transform->iv_dec, transform->ivlen, 1449 data, rec->data_len, data, &olen ) ) != 0 ) 1450 { 1451 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); 1452 return( ret ); 1453 } 1454 1455 /* Double-check that length hasn't changed during decryption. */ 1456 if( rec->data_len != olen ) 1457 { 1458 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1459 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1460 } 1461 1462 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) 1463 if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) 1464 { 1465 /* 1466 * Save IV in SSL3 and TLS1, where CBC decryption of consecutive 1467 * records is equivalent to CBC decryption of the concatenation 1468 * of the records; in other words, IVs are maintained across 1469 * record decryptions. 1470 */ 1471 memcpy( transform->iv_dec, transform->cipher_ctx_dec.iv, 1472 transform->ivlen ); 1473 } 1474 #endif 1475 1476 /* Safe since data_len >= minlen + maclen + 1, so after having 1477 * subtracted at most minlen and maclen up to this point, 1478 * data_len > 0 (because of data_len % ivlen == 0, it's actually 1479 * >= ivlen ). */ 1480 padlen = data[rec->data_len - 1]; 1481 1482 if( auth_done == 1 ) 1483 { 1484 const size_t mask = mbedtls_ct_size_mask_ge( 1485 rec->data_len, 1486 padlen + 1 ); 1487 correct &= mask; 1488 padlen &= mask; 1489 } 1490 else 1491 { 1492 #if defined(MBEDTLS_SSL_DEBUG_ALL) 1493 if( rec->data_len < transform->maclen + padlen + 1 ) 1494 { 1495 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%" MBEDTLS_PRINTF_SIZET 1496 ") < maclen (%" MBEDTLS_PRINTF_SIZET 1497 ") + padlen (%" MBEDTLS_PRINTF_SIZET ")", 1498 rec->data_len, 1499 transform->maclen, 1500 padlen + 1 ) ); 1501 } 1502 #endif 1503 1504 const size_t mask = mbedtls_ct_size_mask_ge( 1505 rec->data_len, 1506 transform->maclen + padlen + 1 ); 1507 correct &= mask; 1508 padlen &= mask; 1509 } 1510 1511 padlen++; 1512 1513 /* Regardless of the validity of the padding, 1514 * we have data_len >= padlen here. */ 1515 1516 #if defined(MBEDTLS_SSL_PROTO_SSL3) 1517 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) 1518 { 1519 /* This is the SSL 3.0 path, we don't have to worry about Lucky 1520 * 13, because there's a strictly worse padding attack built in 1521 * the protocol (known as part of POODLE), so we don't care if the 1522 * code is not constant-time, in particular branches are OK. */ 1523 if( padlen > transform->ivlen ) 1524 { 1525 #if defined(MBEDTLS_SSL_DEBUG_ALL) 1526 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %" MBEDTLS_PRINTF_SIZET ", " 1527 "should be no more than %" MBEDTLS_PRINTF_SIZET, 1528 padlen, transform->ivlen ) ); 1529 #endif 1530 correct = 0; 1531 } 1532 } 1533 else 1534 #endif /* MBEDTLS_SSL_PROTO_SSL3 */ 1535 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ 1536 defined(MBEDTLS_SSL_PROTO_TLS1_2) 1537 if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) 1538 { 1539 /* The padding check involves a series of up to 256 1540 * consecutive memory reads at the end of the record 1541 * plaintext buffer. In order to hide the length and 1542 * validity of the padding, always perform exactly 1543 * `min(256,plaintext_len)` reads (but take into account 1544 * only the last `padlen` bytes for the padding check). */ 1545 size_t pad_count = 0; 1546 volatile unsigned char* const check = data; 1547 1548 /* Index of first padding byte; it has been ensured above 1549 * that the subtraction is safe. */ 1550 size_t const padding_idx = rec->data_len - padlen; 1551 size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256; 1552 size_t const start_idx = rec->data_len - num_checks; 1553 size_t idx; 1554 1555 for( idx = start_idx; idx < rec->data_len; idx++ ) 1556 { 1557 /* pad_count += (idx >= padding_idx) && 1558 * (check[idx] == padlen - 1); 1559 */ 1560 const size_t mask = mbedtls_ct_size_mask_ge( idx, padding_idx ); 1561 const size_t equal = mbedtls_ct_size_bool_eq( check[idx], 1562 padlen - 1 ); 1563 pad_count += mask & equal; 1564 } 1565 correct &= mbedtls_ct_size_bool_eq( pad_count, padlen ); 1566 1567 #if defined(MBEDTLS_SSL_DEBUG_ALL) 1568 if( padlen > 0 && correct == 0 ) 1569 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) ); 1570 #endif 1571 padlen &= mbedtls_ct_size_mask( correct ); 1572 } 1573 else 1574 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ 1575 MBEDTLS_SSL_PROTO_TLS1_2 */ 1576 { 1577 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1578 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1579 } 1580 1581 /* If the padding was found to be invalid, padlen == 0 1582 * and the subtraction is safe. If the padding was found valid, 1583 * padlen hasn't been changed and the previous assertion 1584 * data_len >= padlen still holds. */ 1585 rec->data_len -= padlen; 1586 } 1587 else 1588 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC */ 1589 { 1590 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1591 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1592 } 1593 1594 #if defined(MBEDTLS_SSL_DEBUG_ALL) 1595 MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption", 1596 data, rec->data_len ); 1597 #endif 1598 1599 /* 1600 * Authenticate if not done yet. 1601 * Compute the MAC regardless of the padding result (RFC4346, CBCTIME). 1602 */ 1603 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) 1604 if( auth_done == 0 ) 1605 { 1606 unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD] = { 0 }; 1607 unsigned char mac_peer[MBEDTLS_SSL_MAC_ADD] = { 0 }; 1608 1609 /* If the initial value of padlen was such that 1610 * data_len < maclen + padlen + 1, then padlen 1611 * got reset to 1, and the initial check 1612 * data_len >= minlen + maclen + 1 1613 * guarantees that at this point we still 1614 * have at least data_len >= maclen. 1615 * 1616 * If the initial value of padlen was such that 1617 * data_len >= maclen + padlen + 1, then we have 1618 * subtracted either padlen + 1 (if the padding was correct) 1619 * or 0 (if the padding was incorrect) since then, 1620 * hence data_len >= maclen in any case. 1621 */ 1622 rec->data_len -= transform->maclen; 1623 ssl_extract_add_data_from_record( add_data, &add_data_len, rec, 1624 transform->minor_ver ); 1625 1626 #if defined(MBEDTLS_SSL_PROTO_SSL3) 1627 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) 1628 { 1629 ret = ssl_mac( &transform->md_ctx_dec, 1630 transform->mac_dec, 1631 data, rec->data_len, 1632 rec->ctr, rec->type, 1633 mac_expect ); 1634 if( ret != 0 ) 1635 { 1636 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_mac", ret ); 1637 goto hmac_failed_etm_disabled; 1638 } 1639 memcpy( mac_peer, data + rec->data_len, transform->maclen ); 1640 } 1641 else 1642 #endif /* MBEDTLS_SSL_PROTO_SSL3 */ 1643 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ 1644 defined(MBEDTLS_SSL_PROTO_TLS1_2) 1645 if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) 1646 { 1647 /* 1648 * The next two sizes are the minimum and maximum values of 1649 * data_len over all padlen values. 1650 * 1651 * They're independent of padlen, since we previously did 1652 * data_len -= padlen. 1653 * 1654 * Note that max_len + maclen is never more than the buffer 1655 * length, as we previously did in_msglen -= maclen too. 1656 */ 1657 const size_t max_len = rec->data_len + padlen; 1658 const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0; 1659 1660 ret = mbedtls_ct_hmac( &transform->md_ctx_dec, 1661 add_data, add_data_len, 1662 data, rec->data_len, min_len, max_len, 1663 mac_expect ); 1664 if( ret != 0 ) 1665 { 1666 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ct_hmac", ret ); 1667 goto hmac_failed_etm_disabled; 1668 } 1669 1670 mbedtls_ct_memcpy_offset( mac_peer, data, 1671 rec->data_len, 1672 min_len, max_len, 1673 transform->maclen ); 1674 } 1675 else 1676 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ 1677 MBEDTLS_SSL_PROTO_TLS1_2 */ 1678 { 1679 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1680 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1681 } 1682 1683 #if defined(MBEDTLS_SSL_DEBUG_ALL) 1684 MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen ); 1685 MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", mac_peer, transform->maclen ); 1686 #endif 1687 1688 if( mbedtls_ct_memcmp( mac_peer, mac_expect, 1689 transform->maclen ) != 0 ) 1690 { 1691 #if defined(MBEDTLS_SSL_DEBUG_ALL) 1692 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); 1693 #endif 1694 correct = 0; 1695 } 1696 auth_done++; 1697 1698 hmac_failed_etm_disabled: 1699 mbedtls_platform_zeroize( mac_peer, transform->maclen ); 1700 mbedtls_platform_zeroize( mac_expect, transform->maclen ); 1701 if( ret != 0 ) 1702 return( ret ); 1703 } 1704 1705 /* 1706 * Finally check the correct flag 1707 */ 1708 if( correct == 0 ) 1709 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 1710 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */ 1711 1712 /* Make extra sure authentication was performed, exactly once */ 1713 if( auth_done != 1 ) 1714 { 1715 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1716 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1717 } 1718 1719 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL) 1720 if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 ) 1721 { 1722 /* Remove inner padding and infer true content type. */ 1723 ret = ssl_parse_inner_plaintext( data, &rec->data_len, 1724 &rec->type ); 1725 1726 if( ret != 0 ) 1727 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 1728 } 1729 #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ 1730 1731 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 1732 if( rec->cid_len != 0 ) 1733 { 1734 ret = ssl_parse_inner_plaintext( data, &rec->data_len, 1735 &rec->type ); 1736 if( ret != 0 ) 1737 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 1738 } 1739 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 1740 1741 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) ); 1742 1743 return( 0 ); 1744 } 1745 1746 #undef MAC_NONE 1747 #undef MAC_PLAINTEXT 1748 #undef MAC_CIPHERTEXT 1749 1750 #if defined(MBEDTLS_ZLIB_SUPPORT) 1751 /* 1752 * Compression/decompression functions 1753 */ 1754 MBEDTLS_CHECK_RETURN_CRITICAL 1755 static int ssl_compress_buf( mbedtls_ssl_context *ssl ) 1756 { 1757 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 1758 unsigned char *msg_post = ssl->out_msg; 1759 ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf; 1760 size_t len_pre = ssl->out_msglen; 1761 unsigned char *msg_pre = ssl->compress_buf; 1762 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) 1763 size_t out_buf_len = ssl->out_buf_len; 1764 #else 1765 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; 1766 #endif 1767 1768 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) ); 1769 1770 if( len_pre == 0 ) 1771 return( 0 ); 1772 1773 memcpy( msg_pre, ssl->out_msg, len_pre ); 1774 1775 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", 1776 ssl->out_msglen ) ); 1777 1778 MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload", 1779 ssl->out_msg, ssl->out_msglen ); 1780 1781 ssl->transform_out->ctx_deflate.next_in = msg_pre; 1782 ssl->transform_out->ctx_deflate.avail_in = len_pre; 1783 ssl->transform_out->ctx_deflate.next_out = msg_post; 1784 ssl->transform_out->ctx_deflate.avail_out = out_buf_len - bytes_written; 1785 1786 ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); 1787 if( ret != Z_OK ) 1788 { 1789 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) ); 1790 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); 1791 } 1792 1793 ssl->out_msglen = out_buf_len - 1794 ssl->transform_out->ctx_deflate.avail_out - bytes_written; 1795 1796 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", 1797 ssl->out_msglen ) ); 1798 1799 MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload", 1800 ssl->out_msg, ssl->out_msglen ); 1801 1802 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) ); 1803 1804 return( 0 ); 1805 } 1806 1807 MBEDTLS_CHECK_RETURN_CRITICAL 1808 static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) 1809 { 1810 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 1811 unsigned char *msg_post = ssl->in_msg; 1812 ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf; 1813 size_t len_pre = ssl->in_msglen; 1814 unsigned char *msg_pre = ssl->compress_buf; 1815 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) 1816 size_t in_buf_len = ssl->in_buf_len; 1817 #else 1818 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; 1819 #endif 1820 1821 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) ); 1822 1823 if( len_pre == 0 ) 1824 return( 0 ); 1825 1826 memcpy( msg_pre, ssl->in_msg, len_pre ); 1827 1828 MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", 1829 ssl->in_msglen ) ); 1830 1831 MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload", 1832 ssl->in_msg, ssl->in_msglen ); 1833 1834 ssl->transform_in->ctx_inflate.next_in = msg_pre; 1835 ssl->transform_in->ctx_inflate.avail_in = len_pre; 1836 ssl->transform_in->ctx_inflate.next_out = msg_post; 1837 ssl->transform_in->ctx_inflate.avail_out = in_buf_len - header_bytes; 1838 1839 ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); 1840 if( ret != Z_OK ) 1841 { 1842 MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) ); 1843 return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); 1844 } 1845 1846 ssl->in_msglen = in_buf_len - 1847 ssl->transform_in->ctx_inflate.avail_out - header_bytes; 1848 1849 MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %" MBEDTLS_PRINTF_SIZET ", ", 1850 ssl->in_msglen ) ); 1851 1852 MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload", 1853 ssl->in_msg, ssl->in_msglen ); 1854 1855 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) ); 1856 1857 return( 0 ); 1858 } 1859 #endif /* MBEDTLS_ZLIB_SUPPORT */ 1860 1861 /* 1862 * Fill the input message buffer by appending data to it. 1863 * The amount of data already fetched is in ssl->in_left. 1864 * 1865 * If we return 0, is it guaranteed that (at least) nb_want bytes are 1866 * available (from this read and/or a previous one). Otherwise, an error code 1867 * is returned (possibly EOF or WANT_READ). 1868 * 1869 * With stream transport (TLS) on success ssl->in_left == nb_want, but 1870 * with datagram transport (DTLS) on success ssl->in_left >= nb_want, 1871 * since we always read a whole datagram at once. 1872 * 1873 * For DTLS, it is up to the caller to set ssl->next_record_offset when 1874 * they're done reading a record. 1875 */ 1876 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) 1877 { 1878 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 1879 size_t len; 1880 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) 1881 size_t in_buf_len = ssl->in_buf_len; 1882 #else 1883 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; 1884 #endif 1885 1886 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) ); 1887 1888 if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL ) 1889 { 1890 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " 1891 "or mbedtls_ssl_set_bio()" ) ); 1892 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 1893 } 1894 1895 if( nb_want > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) ) 1896 { 1897 MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) ); 1898 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 1899 } 1900 1901 #if defined(MBEDTLS_SSL_PROTO_DTLS) 1902 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 1903 { 1904 uint32_t timeout; 1905 1906 /* 1907 * The point is, we need to always read a full datagram at once, so we 1908 * sometimes read more then requested, and handle the additional data. 1909 * It could be the rest of the current record (while fetching the 1910 * header) and/or some other records in the same datagram. 1911 */ 1912 1913 /* 1914 * Move to the next record in the already read datagram if applicable 1915 */ 1916 if( ssl->next_record_offset != 0 ) 1917 { 1918 if( ssl->in_left < ssl->next_record_offset ) 1919 { 1920 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1921 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1922 } 1923 1924 ssl->in_left -= ssl->next_record_offset; 1925 1926 if( ssl->in_left != 0 ) 1927 { 1928 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %" 1929 MBEDTLS_PRINTF_SIZET, 1930 ssl->next_record_offset ) ); 1931 memmove( ssl->in_hdr, 1932 ssl->in_hdr + ssl->next_record_offset, 1933 ssl->in_left ); 1934 } 1935 1936 ssl->next_record_offset = 0; 1937 } 1938 1939 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %" MBEDTLS_PRINTF_SIZET 1940 ", nb_want: %" MBEDTLS_PRINTF_SIZET, 1941 ssl->in_left, nb_want ) ); 1942 1943 /* 1944 * Done if we already have enough data. 1945 */ 1946 if( nb_want <= ssl->in_left) 1947 { 1948 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); 1949 return( 0 ); 1950 } 1951 1952 /* 1953 * A record can't be split across datagrams. If we need to read but 1954 * are not at the beginning of a new record, the caller did something 1955 * wrong. 1956 */ 1957 if( ssl->in_left != 0 ) 1958 { 1959 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 1960 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 1961 } 1962 1963 /* 1964 * Don't even try to read if time's out already. 1965 * This avoids by-passing the timer when repeatedly receiving messages 1966 * that will end up being dropped. 1967 */ 1968 if( mbedtls_ssl_check_timer( ssl ) != 0 ) 1969 { 1970 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) ); 1971 ret = MBEDTLS_ERR_SSL_TIMEOUT; 1972 } 1973 else 1974 { 1975 len = in_buf_len - ( ssl->in_hdr - ssl->in_buf ); 1976 1977 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) 1978 timeout = ssl->handshake->retransmit_timeout; 1979 else 1980 timeout = ssl->conf->read_timeout; 1981 1982 MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %lu ms", (unsigned long) timeout ) ); 1983 1984 if( ssl->f_recv_timeout != NULL ) 1985 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len, 1986 timeout ); 1987 else 1988 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len ); 1989 1990 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); 1991 1992 if( ret == 0 ) 1993 return( MBEDTLS_ERR_SSL_CONN_EOF ); 1994 } 1995 1996 if( ret == MBEDTLS_ERR_SSL_TIMEOUT ) 1997 { 1998 MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) ); 1999 mbedtls_ssl_set_timer( ssl, 0 ); 2000 2001 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) 2002 { 2003 if( ssl_double_retransmit_timeout( ssl ) != 0 ) 2004 { 2005 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) ); 2006 return( MBEDTLS_ERR_SSL_TIMEOUT ); 2007 } 2008 2009 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) 2010 { 2011 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); 2012 return( ret ); 2013 } 2014 2015 return( MBEDTLS_ERR_SSL_WANT_READ ); 2016 } 2017 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) 2018 else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && 2019 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) 2020 { 2021 if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 ) 2022 { 2023 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request", 2024 ret ); 2025 return( ret ); 2026 } 2027 2028 return( MBEDTLS_ERR_SSL_WANT_READ ); 2029 } 2030 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ 2031 } 2032 2033 if( ret < 0 ) 2034 return( ret ); 2035 2036 ssl->in_left = ret; 2037 } 2038 else 2039 #endif 2040 { 2041 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %" MBEDTLS_PRINTF_SIZET 2042 ", nb_want: %" MBEDTLS_PRINTF_SIZET, 2043 ssl->in_left, nb_want ) ); 2044 2045 while( ssl->in_left < nb_want ) 2046 { 2047 len = nb_want - ssl->in_left; 2048 2049 if( mbedtls_ssl_check_timer( ssl ) != 0 ) 2050 ret = MBEDTLS_ERR_SSL_TIMEOUT; 2051 else 2052 { 2053 if( ssl->f_recv_timeout != NULL ) 2054 { 2055 ret = ssl->f_recv_timeout( ssl->p_bio, 2056 ssl->in_hdr + ssl->in_left, len, 2057 ssl->conf->read_timeout ); 2058 } 2059 else 2060 { 2061 ret = ssl->f_recv( ssl->p_bio, 2062 ssl->in_hdr + ssl->in_left, len ); 2063 } 2064 } 2065 2066 MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %" MBEDTLS_PRINTF_SIZET 2067 ", nb_want: %" MBEDTLS_PRINTF_SIZET, 2068 ssl->in_left, nb_want ) ); 2069 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); 2070 2071 if( ret == 0 ) 2072 return( MBEDTLS_ERR_SSL_CONN_EOF ); 2073 2074 if( ret < 0 ) 2075 return( ret ); 2076 2077 if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) 2078 { 2079 MBEDTLS_SSL_DEBUG_MSG( 1, 2080 ( "f_recv returned %d bytes but only %" MBEDTLS_PRINTF_SIZET " were requested", 2081 ret, len ) ); 2082 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2083 } 2084 2085 ssl->in_left += ret; 2086 } 2087 } 2088 2089 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); 2090 2091 return( 0 ); 2092 } 2093 2094 /* 2095 * Flush any data not yet written 2096 */ 2097 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) 2098 { 2099 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 2100 unsigned char *buf; 2101 2102 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) ); 2103 2104 if( ssl->f_send == NULL ) 2105 { 2106 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " 2107 "or mbedtls_ssl_set_bio()" ) ); 2108 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 2109 } 2110 2111 /* Avoid incrementing counter if data is flushed */ 2112 if( ssl->out_left == 0 ) 2113 { 2114 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); 2115 return( 0 ); 2116 } 2117 2118 while( ssl->out_left > 0 ) 2119 { 2120 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %" MBEDTLS_PRINTF_SIZET 2121 ", out_left: %" MBEDTLS_PRINTF_SIZET, 2122 mbedtls_ssl_out_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) ); 2123 2124 buf = ssl->out_hdr - ssl->out_left; 2125 ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left ); 2126 2127 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret ); 2128 2129 if( ret <= 0 ) 2130 return( ret ); 2131 2132 if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > (int)SIZE_MAX ) ) 2133 { 2134 MBEDTLS_SSL_DEBUG_MSG( 1, 2135 ( "f_send returned %d bytes but only %" MBEDTLS_PRINTF_SIZET " bytes were sent", 2136 ret, ssl->out_left ) ); 2137 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2138 } 2139 2140 ssl->out_left -= ret; 2141 } 2142 2143 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2144 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 2145 { 2146 ssl->out_hdr = ssl->out_buf; 2147 } 2148 else 2149 #endif 2150 { 2151 ssl->out_hdr = ssl->out_buf + 8; 2152 } 2153 mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); 2154 2155 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); 2156 2157 return( 0 ); 2158 } 2159 2160 /* 2161 * Functions to handle the DTLS retransmission state machine 2162 */ 2163 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2164 /* 2165 * Append current handshake message to current outgoing flight 2166 */ 2167 MBEDTLS_CHECK_RETURN_CRITICAL 2168 static int ssl_flight_append( mbedtls_ssl_context *ssl ) 2169 { 2170 mbedtls_ssl_flight_item *msg; 2171 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) ); 2172 MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight", 2173 ssl->out_msg, ssl->out_msglen ); 2174 2175 /* Allocate space for current message */ 2176 if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL ) 2177 { 2178 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %" MBEDTLS_PRINTF_SIZET " bytes failed", 2179 sizeof( mbedtls_ssl_flight_item ) ) ); 2180 return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); 2181 } 2182 2183 if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL ) 2184 { 2185 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %" MBEDTLS_PRINTF_SIZET " bytes failed", 2186 ssl->out_msglen ) ); 2187 mbedtls_free( msg ); 2188 return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); 2189 } 2190 2191 /* Copy current handshake message with headers */ 2192 memcpy( msg->p, ssl->out_msg, ssl->out_msglen ); 2193 msg->len = ssl->out_msglen; 2194 msg->type = ssl->out_msgtype; 2195 msg->next = NULL; 2196 2197 /* Append to the current flight */ 2198 if( ssl->handshake->flight == NULL ) 2199 ssl->handshake->flight = msg; 2200 else 2201 { 2202 mbedtls_ssl_flight_item *cur = ssl->handshake->flight; 2203 while( cur->next != NULL ) 2204 cur = cur->next; 2205 cur->next = msg; 2206 } 2207 2208 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) ); 2209 return( 0 ); 2210 } 2211 2212 /* 2213 * Free the current flight of handshake messages 2214 */ 2215 void mbedtls_ssl_flight_free( mbedtls_ssl_flight_item *flight ) 2216 { 2217 mbedtls_ssl_flight_item *cur = flight; 2218 mbedtls_ssl_flight_item *next; 2219 2220 while( cur != NULL ) 2221 { 2222 next = cur->next; 2223 2224 mbedtls_free( cur->p ); 2225 mbedtls_free( cur ); 2226 2227 cur = next; 2228 } 2229 } 2230 2231 /* 2232 * Swap transform_out and out_ctr with the alternative ones 2233 */ 2234 MBEDTLS_CHECK_RETURN_CRITICAL 2235 static int ssl_swap_epochs( mbedtls_ssl_context *ssl ) 2236 { 2237 mbedtls_ssl_transform *tmp_transform; 2238 unsigned char tmp_out_ctr[8]; 2239 2240 if( ssl->transform_out == ssl->handshake->alt_transform_out ) 2241 { 2242 MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) ); 2243 return( 0 ); 2244 } 2245 2246 MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) ); 2247 2248 /* Swap transforms */ 2249 tmp_transform = ssl->transform_out; 2250 ssl->transform_out = ssl->handshake->alt_transform_out; 2251 ssl->handshake->alt_transform_out = tmp_transform; 2252 2253 /* Swap epoch + sequence_number */ 2254 memcpy( tmp_out_ctr, ssl->cur_out_ctr, 8 ); 2255 memcpy( ssl->cur_out_ctr, ssl->handshake->alt_out_ctr, 8 ); 2256 memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 ); 2257 2258 /* Adjust to the newly activated transform */ 2259 mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); 2260 2261 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) 2262 if( mbedtls_ssl_hw_record_activate != NULL ) 2263 { 2264 int ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ); 2265 if( ret != 0 ) 2266 { 2267 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); 2268 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); 2269 } 2270 } 2271 #endif 2272 2273 return( 0 ); 2274 } 2275 2276 /* 2277 * Retransmit the current flight of messages. 2278 */ 2279 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ) 2280 { 2281 int ret = 0; 2282 2283 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) ); 2284 2285 ret = mbedtls_ssl_flight_transmit( ssl ); 2286 2287 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) ); 2288 2289 return( ret ); 2290 } 2291 2292 /* 2293 * Transmit or retransmit the current flight of messages. 2294 * 2295 * Need to remember the current message in case flush_output returns 2296 * WANT_WRITE, causing us to exit this function and come back later. 2297 * This function must be called until state is no longer SENDING. 2298 */ 2299 int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl ) 2300 { 2301 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 2302 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) ); 2303 2304 if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING ) 2305 { 2306 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) ); 2307 2308 ssl->handshake->cur_msg = ssl->handshake->flight; 2309 ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12; 2310 ret = ssl_swap_epochs( ssl ); 2311 if( ret != 0 ) 2312 return( ret ); 2313 2314 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING; 2315 } 2316 2317 while( ssl->handshake->cur_msg != NULL ) 2318 { 2319 size_t max_frag_len; 2320 const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg; 2321 2322 int const is_finished = 2323 ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE && 2324 cur->p[0] == MBEDTLS_SSL_HS_FINISHED ); 2325 2326 uint8_t const force_flush = ssl->disable_datagram_packing == 1 ? 2327 SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH; 2328 2329 /* Swap epochs before sending Finished: we can't do it after 2330 * sending ChangeCipherSpec, in case write returns WANT_READ. 2331 * Must be done before copying, may change out_msg pointer */ 2332 if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) ) 2333 { 2334 MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) ); 2335 ret = ssl_swap_epochs( ssl ); 2336 if( ret != 0 ) 2337 return( ret ); 2338 } 2339 2340 ret = ssl_get_remaining_payload_in_datagram( ssl ); 2341 if( ret < 0 ) 2342 return( ret ); 2343 max_frag_len = (size_t) ret; 2344 2345 /* CCS is copied as is, while HS messages may need fragmentation */ 2346 if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) 2347 { 2348 if( max_frag_len == 0 ) 2349 { 2350 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) 2351 return( ret ); 2352 2353 continue; 2354 } 2355 2356 memcpy( ssl->out_msg, cur->p, cur->len ); 2357 ssl->out_msglen = cur->len; 2358 ssl->out_msgtype = cur->type; 2359 2360 /* Update position inside current message */ 2361 ssl->handshake->cur_msg_p += cur->len; 2362 } 2363 else 2364 { 2365 const unsigned char * const p = ssl->handshake->cur_msg_p; 2366 const size_t hs_len = cur->len - 12; 2367 const size_t frag_off = p - ( cur->p + 12 ); 2368 const size_t rem_len = hs_len - frag_off; 2369 size_t cur_hs_frag_len, max_hs_frag_len; 2370 2371 if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) ) 2372 { 2373 if( is_finished ) 2374 { 2375 ret = ssl_swap_epochs( ssl ); 2376 if( ret != 0 ) 2377 return( ret ); 2378 } 2379 2380 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) 2381 return( ret ); 2382 2383 continue; 2384 } 2385 max_hs_frag_len = max_frag_len - 12; 2386 2387 cur_hs_frag_len = rem_len > max_hs_frag_len ? 2388 max_hs_frag_len : rem_len; 2389 2390 if( frag_off == 0 && cur_hs_frag_len != hs_len ) 2391 { 2392 MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)", 2393 (unsigned) cur_hs_frag_len, 2394 (unsigned) max_hs_frag_len ) ); 2395 } 2396 2397 /* Messages are stored with handshake headers as if not fragmented, 2398 * copy beginning of headers then fill fragmentation fields. 2399 * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */ 2400 memcpy( ssl->out_msg, cur->p, 6 ); 2401 2402 ssl->out_msg[6] = MBEDTLS_BYTE_2( frag_off ); 2403 ssl->out_msg[7] = MBEDTLS_BYTE_1( frag_off ); 2404 ssl->out_msg[8] = MBEDTLS_BYTE_0( frag_off ); 2405 2406 ssl->out_msg[ 9] = MBEDTLS_BYTE_2( cur_hs_frag_len ); 2407 ssl->out_msg[10] = MBEDTLS_BYTE_1( cur_hs_frag_len ); 2408 ssl->out_msg[11] = MBEDTLS_BYTE_0( cur_hs_frag_len ); 2409 2410 MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 ); 2411 2412 /* Copy the handshake message content and set records fields */ 2413 memcpy( ssl->out_msg + 12, p, cur_hs_frag_len ); 2414 ssl->out_msglen = cur_hs_frag_len + 12; 2415 ssl->out_msgtype = cur->type; 2416 2417 /* Update position inside current message */ 2418 ssl->handshake->cur_msg_p += cur_hs_frag_len; 2419 } 2420 2421 /* If done with the current message move to the next one if any */ 2422 if( ssl->handshake->cur_msg_p >= cur->p + cur->len ) 2423 { 2424 if( cur->next != NULL ) 2425 { 2426 ssl->handshake->cur_msg = cur->next; 2427 ssl->handshake->cur_msg_p = cur->next->p + 12; 2428 } 2429 else 2430 { 2431 ssl->handshake->cur_msg = NULL; 2432 ssl->handshake->cur_msg_p = NULL; 2433 } 2434 } 2435 2436 /* Actually send the message out */ 2437 if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 ) 2438 { 2439 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); 2440 return( ret ); 2441 } 2442 } 2443 2444 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) 2445 return( ret ); 2446 2447 /* Update state and set timer */ 2448 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) 2449 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; 2450 else 2451 { 2452 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; 2453 mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); 2454 } 2455 2456 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) ); 2457 2458 return( 0 ); 2459 } 2460 2461 /* 2462 * To be called when the last message of an incoming flight is received. 2463 */ 2464 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ) 2465 { 2466 /* We won't need to resend that one any more */ 2467 mbedtls_ssl_flight_free( ssl->handshake->flight ); 2468 ssl->handshake->flight = NULL; 2469 ssl->handshake->cur_msg = NULL; 2470 2471 /* The next incoming flight will start with this msg_seq */ 2472 ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq; 2473 2474 /* We don't want to remember CCS's across flight boundaries. */ 2475 ssl->handshake->buffering.seen_ccs = 0; 2476 2477 /* Clear future message buffering structure. */ 2478 mbedtls_ssl_buffering_free( ssl ); 2479 2480 /* Cancel timer */ 2481 mbedtls_ssl_set_timer( ssl, 0 ); 2482 2483 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && 2484 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) 2485 { 2486 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; 2487 } 2488 else 2489 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; 2490 } 2491 2492 /* 2493 * To be called when the last message of an outgoing flight is send. 2494 */ 2495 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ) 2496 { 2497 ssl_reset_retransmit_timeout( ssl ); 2498 mbedtls_ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); 2499 2500 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && 2501 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) 2502 { 2503 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; 2504 } 2505 else 2506 ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; 2507 } 2508 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 2509 2510 /* 2511 * Handshake layer functions 2512 */ 2513 2514 /* 2515 * Write (DTLS: or queue) current handshake (including CCS) message. 2516 * 2517 * - fill in handshake headers 2518 * - update handshake checksum 2519 * - DTLS: save message for resending 2520 * - then pass to the record layer 2521 * 2522 * DTLS: except for HelloRequest, messages are only queued, and will only be 2523 * actually sent when calling flight_transmit() or resend(). 2524 * 2525 * Inputs: 2526 * - ssl->out_msglen: 4 + actual handshake message len 2527 * (4 is the size of handshake headers for TLS) 2528 * - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc) 2529 * - ssl->out_msg + 4: the handshake message body 2530 * 2531 * Outputs, ie state before passing to flight_append() or write_record(): 2532 * - ssl->out_msglen: the length of the record contents 2533 * (including handshake headers but excluding record headers) 2534 * - ssl->out_msg: the record contents (handshake headers + content) 2535 */ 2536 int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl ) 2537 { 2538 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 2539 const size_t hs_len = ssl->out_msglen - 4; 2540 const unsigned char hs_type = ssl->out_msg[0]; 2541 2542 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) ); 2543 2544 /* 2545 * Sanity checks 2546 */ 2547 if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE && 2548 ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) 2549 { 2550 /* In SSLv3, the client might send a NoCertificate alert. */ 2551 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) 2552 if( ! ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && 2553 ssl->out_msgtype == MBEDTLS_SSL_MSG_ALERT && 2554 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ) 2555 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ 2556 { 2557 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 2558 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2559 } 2560 } 2561 2562 /* Whenever we send anything different from a 2563 * HelloRequest we should be in a handshake - double check. */ 2564 if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && 2565 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) && 2566 ssl->handshake == NULL ) 2567 { 2568 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 2569 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2570 } 2571 2572 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2573 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 2574 ssl->handshake != NULL && 2575 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) 2576 { 2577 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 2578 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2579 } 2580 #endif 2581 2582 /* Double-check that we did not exceed the bounds 2583 * of the outgoing record buffer. 2584 * This should never fail as the various message 2585 * writing functions must obey the bounds of the 2586 * outgoing record buffer, but better be safe. 2587 * 2588 * Note: We deliberately do not check for the MTU or MFL here. 2589 */ 2590 if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN ) 2591 { 2592 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: " 2593 "size %" MBEDTLS_PRINTF_SIZET 2594 ", maximum %" MBEDTLS_PRINTF_SIZET, 2595 ssl->out_msglen, 2596 (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN ) ); 2597 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2598 } 2599 2600 /* 2601 * Fill handshake headers 2602 */ 2603 if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) 2604 { 2605 ssl->out_msg[1] = MBEDTLS_BYTE_2( hs_len ); 2606 ssl->out_msg[2] = MBEDTLS_BYTE_1( hs_len ); 2607 ssl->out_msg[3] = MBEDTLS_BYTE_0( hs_len ); 2608 2609 /* 2610 * DTLS has additional fields in the Handshake layer, 2611 * between the length field and the actual payload: 2612 * uint16 message_seq; 2613 * uint24 fragment_offset; 2614 * uint24 fragment_length; 2615 */ 2616 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2617 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 2618 { 2619 /* Make room for the additional DTLS fields */ 2620 if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 ) 2621 { 2622 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: " 2623 "size %" MBEDTLS_PRINTF_SIZET ", maximum %" MBEDTLS_PRINTF_SIZET, 2624 hs_len, 2625 (size_t) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) ); 2626 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 2627 } 2628 2629 memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len ); 2630 ssl->out_msglen += 8; 2631 2632 /* Write message_seq and update it, except for HelloRequest */ 2633 if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) 2634 { 2635 MBEDTLS_PUT_UINT16_BE( ssl->handshake->out_msg_seq, ssl->out_msg, 4 ); 2636 ++( ssl->handshake->out_msg_seq ); 2637 } 2638 else 2639 { 2640 ssl->out_msg[4] = 0; 2641 ssl->out_msg[5] = 0; 2642 } 2643 2644 /* Handshake hashes are computed without fragmentation, 2645 * so set frag_offset = 0 and frag_len = hs_len for now */ 2646 memset( ssl->out_msg + 6, 0x00, 3 ); 2647 memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 ); 2648 } 2649 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 2650 2651 /* Update running hashes of handshake messages seen */ 2652 if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) 2653 ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen ); 2654 } 2655 2656 /* Either send now, or just save to be sent (and resent) later */ 2657 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2658 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 2659 ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && 2660 hs_type == MBEDTLS_SSL_HS_HELLO_REQUEST ) ) 2661 { 2662 if( ( ret = ssl_flight_append( ssl ) ) != 0 ) 2663 { 2664 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret ); 2665 return( ret ); 2666 } 2667 } 2668 else 2669 #endif 2670 { 2671 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) 2672 { 2673 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret ); 2674 return( ret ); 2675 } 2676 } 2677 2678 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) ); 2679 2680 return( 0 ); 2681 } 2682 2683 /* 2684 * Record layer functions 2685 */ 2686 2687 /* 2688 * Write current record. 2689 * 2690 * Uses: 2691 * - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS) 2692 * - ssl->out_msglen: length of the record content (excl headers) 2693 * - ssl->out_msg: record content 2694 */ 2695 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush ) 2696 { 2697 int ret, done = 0; 2698 size_t len = ssl->out_msglen; 2699 uint8_t flush = force_flush; 2700 2701 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) ); 2702 2703 #if defined(MBEDTLS_ZLIB_SUPPORT) 2704 if( ssl->transform_out != NULL && 2705 ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) 2706 { 2707 if( ( ret = ssl_compress_buf( ssl ) ) != 0 ) 2708 { 2709 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret ); 2710 return( ret ); 2711 } 2712 2713 len = ssl->out_msglen; 2714 } 2715 #endif /*MBEDTLS_ZLIB_SUPPORT */ 2716 2717 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) 2718 if( mbedtls_ssl_hw_record_write != NULL ) 2719 { 2720 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) ); 2721 2722 ret = mbedtls_ssl_hw_record_write( ssl ); 2723 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) 2724 { 2725 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret ); 2726 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); 2727 } 2728 2729 if( ret == 0 ) 2730 done = 1; 2731 } 2732 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ 2733 if( !done ) 2734 { 2735 unsigned i; 2736 size_t protected_record_size; 2737 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) 2738 size_t out_buf_len = ssl->out_buf_len; 2739 #else 2740 size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN; 2741 #endif 2742 /* Skip writing the record content type to after the encryption, 2743 * as it may change when using the CID extension. */ 2744 2745 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, 2746 ssl->conf->transport, ssl->out_hdr + 1 ); 2747 2748 memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 ); 2749 MBEDTLS_PUT_UINT16_BE( len, ssl->out_len, 0); 2750 2751 if( ssl->transform_out != NULL ) 2752 { 2753 mbedtls_record rec; 2754 2755 rec.buf = ssl->out_iv; 2756 rec.buf_len = out_buf_len - ( ssl->out_iv - ssl->out_buf ); 2757 rec.data_len = ssl->out_msglen; 2758 rec.data_offset = ssl->out_msg - rec.buf; 2759 2760 memcpy( &rec.ctr[0], ssl->out_ctr, 8 ); 2761 mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, 2762 ssl->conf->transport, rec.ver ); 2763 rec.type = ssl->out_msgtype; 2764 2765 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 2766 /* The CID is set by mbedtls_ssl_encrypt_buf(). */ 2767 rec.cid_len = 0; 2768 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 2769 2770 if( ( ret = mbedtls_ssl_encrypt_buf( ssl, ssl->transform_out, &rec, 2771 ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) 2772 { 2773 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret ); 2774 return( ret ); 2775 } 2776 2777 if( rec.data_offset != 0 ) 2778 { 2779 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 2780 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2781 } 2782 2783 /* Update the record content type and CID. */ 2784 ssl->out_msgtype = rec.type; 2785 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID ) 2786 memcpy( ssl->out_cid, rec.cid, rec.cid_len ); 2787 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 2788 ssl->out_msglen = len = rec.data_len; 2789 MBEDTLS_PUT_UINT16_BE( rec.data_len, ssl->out_len, 0 ); 2790 } 2791 2792 protected_record_size = len + mbedtls_ssl_out_hdr_len( ssl ); 2793 2794 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2795 /* In case of DTLS, double-check that we don't exceed 2796 * the remaining space in the datagram. */ 2797 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 2798 { 2799 ret = ssl_get_remaining_space_in_datagram( ssl ); 2800 if( ret < 0 ) 2801 return( ret ); 2802 2803 if( protected_record_size > (size_t) ret ) 2804 { 2805 /* Should never happen */ 2806 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 2807 } 2808 } 2809 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 2810 2811 /* Now write the potentially updated record content type. */ 2812 ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype; 2813 2814 MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %u, " 2815 "version = [%u:%u], msglen = %" MBEDTLS_PRINTF_SIZET, 2816 ssl->out_hdr[0], ssl->out_hdr[1], 2817 ssl->out_hdr[2], len ) ); 2818 2819 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", 2820 ssl->out_hdr, protected_record_size ); 2821 2822 ssl->out_left += protected_record_size; 2823 ssl->out_hdr += protected_record_size; 2824 mbedtls_ssl_update_out_pointers( ssl, ssl->transform_out ); 2825 2826 for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- ) 2827 if( ++ssl->cur_out_ctr[i - 1] != 0 ) 2828 break; 2829 2830 /* The loop goes to its end iff the counter is wrapping */ 2831 if( i == mbedtls_ssl_ep_len( ssl ) ) 2832 { 2833 MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) ); 2834 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); 2835 } 2836 } 2837 2838 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2839 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 2840 flush == SSL_DONT_FORCE_FLUSH ) 2841 { 2842 size_t remaining; 2843 ret = ssl_get_remaining_payload_in_datagram( ssl ); 2844 if( ret < 0 ) 2845 { 2846 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram", 2847 ret ); 2848 return( ret ); 2849 } 2850 2851 remaining = (size_t) ret; 2852 if( remaining == 0 ) 2853 { 2854 flush = SSL_FORCE_FLUSH; 2855 } 2856 else 2857 { 2858 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) ); 2859 } 2860 } 2861 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 2862 2863 if( ( flush == SSL_FORCE_FLUSH ) && 2864 ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) 2865 { 2866 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); 2867 return( ret ); 2868 } 2869 2870 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) ); 2871 2872 return( 0 ); 2873 } 2874 2875 #if defined(MBEDTLS_SSL_PROTO_DTLS) 2876 2877 MBEDTLS_CHECK_RETURN_CRITICAL 2878 static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl ) 2879 { 2880 if( ssl->in_msglen < ssl->in_hslen || 2881 memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 || 2882 memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 ) 2883 { 2884 return( 1 ); 2885 } 2886 return( 0 ); 2887 } 2888 2889 static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl ) 2890 { 2891 return( ( ssl->in_msg[9] << 16 ) | 2892 ( ssl->in_msg[10] << 8 ) | 2893 ssl->in_msg[11] ); 2894 } 2895 2896 static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl ) 2897 { 2898 return( ( ssl->in_msg[6] << 16 ) | 2899 ( ssl->in_msg[7] << 8 ) | 2900 ssl->in_msg[8] ); 2901 } 2902 2903 MBEDTLS_CHECK_RETURN_CRITICAL 2904 static int ssl_check_hs_header( mbedtls_ssl_context const *ssl ) 2905 { 2906 uint32_t msg_len, frag_off, frag_len; 2907 2908 msg_len = ssl_get_hs_total_len( ssl ); 2909 frag_off = ssl_get_hs_frag_off( ssl ); 2910 frag_len = ssl_get_hs_frag_len( ssl ); 2911 2912 if( frag_off > msg_len ) 2913 return( -1 ); 2914 2915 if( frag_len > msg_len - frag_off ) 2916 return( -1 ); 2917 2918 if( frag_len + 12 > ssl->in_msglen ) 2919 return( -1 ); 2920 2921 return( 0 ); 2922 } 2923 2924 /* 2925 * Mark bits in bitmask (used for DTLS HS reassembly) 2926 */ 2927 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len ) 2928 { 2929 unsigned int start_bits, end_bits; 2930 2931 start_bits = 8 - ( offset % 8 ); 2932 if( start_bits != 8 ) 2933 { 2934 size_t first_byte_idx = offset / 8; 2935 2936 /* Special case */ 2937 if( len <= start_bits ) 2938 { 2939 for( ; len != 0; len-- ) 2940 mask[first_byte_idx] |= 1 << ( start_bits - len ); 2941 2942 /* Avoid potential issues with offset or len becoming invalid */ 2943 return; 2944 } 2945 2946 offset += start_bits; /* Now offset % 8 == 0 */ 2947 len -= start_bits; 2948 2949 for( ; start_bits != 0; start_bits-- ) 2950 mask[first_byte_idx] |= 1 << ( start_bits - 1 ); 2951 } 2952 2953 end_bits = len % 8; 2954 if( end_bits != 0 ) 2955 { 2956 size_t last_byte_idx = ( offset + len ) / 8; 2957 2958 len -= end_bits; /* Now len % 8 == 0 */ 2959 2960 for( ; end_bits != 0; end_bits-- ) 2961 mask[last_byte_idx] |= 1 << ( 8 - end_bits ); 2962 } 2963 2964 memset( mask + offset / 8, 0xFF, len / 8 ); 2965 } 2966 2967 /* 2968 * Check that bitmask is full 2969 */ 2970 MBEDTLS_CHECK_RETURN_CRITICAL 2971 static int ssl_bitmask_check( unsigned char *mask, size_t len ) 2972 { 2973 size_t i; 2974 2975 for( i = 0; i < len / 8; i++ ) 2976 if( mask[i] != 0xFF ) 2977 return( -1 ); 2978 2979 for( i = 0; i < len % 8; i++ ) 2980 if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 ) 2981 return( -1 ); 2982 2983 return( 0 ); 2984 } 2985 2986 /* msg_len does not include the handshake header */ 2987 static size_t ssl_get_reassembly_buffer_size( size_t msg_len, 2988 unsigned add_bitmap ) 2989 { 2990 size_t alloc_len; 2991 2992 alloc_len = 12; /* Handshake header */ 2993 alloc_len += msg_len; /* Content buffer */ 2994 2995 if( add_bitmap ) 2996 alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap */ 2997 2998 return( alloc_len ); 2999 } 3000 3001 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3002 3003 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl ) 3004 { 3005 return( ( ssl->in_msg[1] << 16 ) | 3006 ( ssl->in_msg[2] << 8 ) | 3007 ssl->in_msg[3] ); 3008 } 3009 3010 int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) 3011 { 3012 if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) ) 3013 { 3014 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %" MBEDTLS_PRINTF_SIZET, 3015 ssl->in_msglen ) ); 3016 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3017 } 3018 3019 ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl ); 3020 3021 MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" 3022 " %" MBEDTLS_PRINTF_SIZET ", type = %u, hslen = %" MBEDTLS_PRINTF_SIZET, 3023 ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); 3024 3025 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3026 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 3027 { 3028 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 3029 unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; 3030 3031 if( ssl_check_hs_header( ssl ) != 0 ) 3032 { 3033 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) ); 3034 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3035 } 3036 3037 if( ssl->handshake != NULL && 3038 ( ( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && 3039 recv_msg_seq != ssl->handshake->in_msg_seq ) || 3040 ( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && 3041 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) ) 3042 { 3043 if( recv_msg_seq > ssl->handshake->in_msg_seq ) 3044 { 3045 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)", 3046 recv_msg_seq, 3047 ssl->handshake->in_msg_seq ) ); 3048 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); 3049 } 3050 3051 /* Retransmit only on last message from previous flight, to avoid 3052 * too many retransmissions. 3053 * Besides, No sane server ever retransmits HelloVerifyRequest */ 3054 if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 && 3055 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) 3056 { 3057 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, " 3058 "message_seq = %u, start_of_flight = %u", 3059 recv_msg_seq, 3060 ssl->handshake->in_flight_start_seq ) ); 3061 3062 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) 3063 { 3064 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); 3065 return( ret ); 3066 } 3067 } 3068 else 3069 { 3070 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: " 3071 "message_seq = %u, expected = %u", 3072 recv_msg_seq, 3073 ssl->handshake->in_msg_seq ) ); 3074 } 3075 3076 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); 3077 } 3078 /* Wait until message completion to increment in_msg_seq */ 3079 3080 /* Message reassembly is handled alongside buffering of future 3081 * messages; the commonality is that both handshake fragments and 3082 * future messages cannot be forwarded immediately to the 3083 * handshake logic layer. */ 3084 if( ssl_hs_is_proper_fragment( ssl ) == 1 ) 3085 { 3086 MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) ); 3087 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); 3088 } 3089 } 3090 else 3091 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3092 /* With TLS we don't handle fragmentation (for now) */ 3093 if( ssl->in_msglen < ssl->in_hslen ) 3094 { 3095 MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) ); 3096 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); 3097 } 3098 3099 return( 0 ); 3100 } 3101 3102 void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ) 3103 { 3104 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 3105 3106 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL ) 3107 { 3108 ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); 3109 } 3110 3111 /* Handshake message is complete, increment counter */ 3112 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3113 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 3114 ssl->handshake != NULL ) 3115 { 3116 unsigned offset; 3117 mbedtls_ssl_hs_buffer *hs_buf; 3118 3119 /* Increment handshake sequence number */ 3120 hs->in_msg_seq++; 3121 3122 /* 3123 * Clear up handshake buffering and reassembly structure. 3124 */ 3125 3126 /* Free first entry */ 3127 ssl_buffering_free_slot( ssl, 0 ); 3128 3129 /* Shift all other entries */ 3130 for( offset = 0, hs_buf = &hs->buffering.hs[0]; 3131 offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS; 3132 offset++, hs_buf++ ) 3133 { 3134 *hs_buf = *(hs_buf + 1); 3135 } 3136 3137 /* Create a fresh last entry */ 3138 memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) ); 3139 } 3140 #endif 3141 } 3142 3143 /* 3144 * DTLS anti-replay: RFC 6347 4.1.2.6 3145 * 3146 * in_window is a field of bits numbered from 0 (lsb) to 63 (msb). 3147 * Bit n is set iff record number in_window_top - n has been seen. 3148 * 3149 * Usually, in_window_top is the last record number seen and the lsb of 3150 * in_window is set. The only exception is the initial state (record number 0 3151 * not seen yet). 3152 */ 3153 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) 3154 void mbedtls_ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ) 3155 { 3156 ssl->in_window_top = 0; 3157 ssl->in_window = 0; 3158 } 3159 3160 static inline uint64_t ssl_load_six_bytes( unsigned char *buf ) 3161 { 3162 return( ( (uint64_t) buf[0] << 40 ) | 3163 ( (uint64_t) buf[1] << 32 ) | 3164 ( (uint64_t) buf[2] << 24 ) | 3165 ( (uint64_t) buf[3] << 16 ) | 3166 ( (uint64_t) buf[4] << 8 ) | 3167 ( (uint64_t) buf[5] ) ); 3168 } 3169 3170 MBEDTLS_CHECK_RETURN_CRITICAL 3171 static int mbedtls_ssl_dtls_record_replay_check( mbedtls_ssl_context *ssl, uint8_t *record_in_ctr ) 3172 { 3173 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 3174 unsigned char *original_in_ctr; 3175 3176 // save original in_ctr 3177 original_in_ctr = ssl->in_ctr; 3178 3179 // use counter from record 3180 ssl->in_ctr = record_in_ctr; 3181 3182 ret = mbedtls_ssl_dtls_replay_check( (mbedtls_ssl_context const *) ssl ); 3183 3184 // restore the counter 3185 ssl->in_ctr = original_in_ctr; 3186 3187 return ret; 3188 } 3189 3190 /* 3191 * Return 0 if sequence number is acceptable, -1 otherwise 3192 */ 3193 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context const *ssl ) 3194 { 3195 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); 3196 uint64_t bit; 3197 3198 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) 3199 return( 0 ); 3200 3201 if( rec_seqnum > ssl->in_window_top ) 3202 return( 0 ); 3203 3204 bit = ssl->in_window_top - rec_seqnum; 3205 3206 if( bit >= 64 ) 3207 return( -1 ); 3208 3209 if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 ) 3210 return( -1 ); 3211 3212 return( 0 ); 3213 } 3214 3215 /* 3216 * Update replay window on new validated record 3217 */ 3218 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ) 3219 { 3220 uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); 3221 3222 if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) 3223 return; 3224 3225 if( rec_seqnum > ssl->in_window_top ) 3226 { 3227 /* Update window_top and the contents of the window */ 3228 uint64_t shift = rec_seqnum - ssl->in_window_top; 3229 3230 if( shift >= 64 ) 3231 ssl->in_window = 1; 3232 else 3233 { 3234 ssl->in_window <<= shift; 3235 ssl->in_window |= 1; 3236 } 3237 3238 ssl->in_window_top = rec_seqnum; 3239 } 3240 else 3241 { 3242 /* Mark that number as seen in the current window */ 3243 uint64_t bit = ssl->in_window_top - rec_seqnum; 3244 3245 if( bit < 64 ) /* Always true, but be extra sure */ 3246 ssl->in_window |= (uint64_t) 1 << bit; 3247 } 3248 } 3249 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ 3250 3251 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) 3252 /* 3253 * Check if a datagram looks like a ClientHello with a valid cookie, 3254 * and if it doesn't, generate a HelloVerifyRequest message. 3255 * Both input and output include full DTLS headers. 3256 * 3257 * - if cookie is valid, return 0 3258 * - if ClientHello looks superficially valid but cookie is not, 3259 * fill obuf and set olen, then 3260 * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED 3261 * - otherwise return a specific error code 3262 */ 3263 MBEDTLS_CHECK_RETURN_CRITICAL 3264 MBEDTLS_STATIC_TESTABLE 3265 int mbedtls_ssl_check_dtls_clihlo_cookie( 3266 mbedtls_ssl_context *ssl, 3267 const unsigned char *cli_id, size_t cli_id_len, 3268 const unsigned char *in, size_t in_len, 3269 unsigned char *obuf, size_t buf_len, size_t *olen ) 3270 { 3271 size_t sid_len, cookie_len; 3272 unsigned char *p; 3273 3274 /* 3275 * Structure of ClientHello with record and handshake headers, 3276 * and expected values. We don't need to check a lot, more checks will be 3277 * done when actually parsing the ClientHello - skipping those checks 3278 * avoids code duplication and does not make cookie forging any easier. 3279 * 3280 * 0-0 ContentType type; copied, must be handshake 3281 * 1-2 ProtocolVersion version; copied 3282 * 3-4 uint16 epoch; copied, must be 0 3283 * 5-10 uint48 sequence_number; copied 3284 * 11-12 uint16 length; (ignored) 3285 * 3286 * 13-13 HandshakeType msg_type; (ignored) 3287 * 14-16 uint24 length; (ignored) 3288 * 17-18 uint16 message_seq; copied 3289 * 19-21 uint24 fragment_offset; copied, must be 0 3290 * 22-24 uint24 fragment_length; (ignored) 3291 * 3292 * 25-26 ProtocolVersion client_version; (ignored) 3293 * 27-58 Random random; (ignored) 3294 * 59-xx SessionID session_id; 1 byte len + sid_len content 3295 * 60+ opaque cookie<0..2^8-1>; 1 byte len + content 3296 * ... 3297 * 3298 * Minimum length is 61 bytes. 3299 */ 3300 MBEDTLS_SSL_DEBUG_MSG( 4, ( "check cookie: in_len=%u", 3301 (unsigned) in_len ) ); 3302 MBEDTLS_SSL_DEBUG_BUF( 4, "cli_id", cli_id, cli_id_len ); 3303 if( in_len < 61 ) 3304 { 3305 MBEDTLS_SSL_DEBUG_MSG( 4, ( "check cookie: record too short" ) ); 3306 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); 3307 } 3308 if( in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || 3309 in[3] != 0 || in[4] != 0 || 3310 in[19] != 0 || in[20] != 0 || in[21] != 0 ) 3311 { 3312 MBEDTLS_SSL_DEBUG_MSG( 4, ( "check cookie: not a good ClientHello" ) ); 3313 MBEDTLS_SSL_DEBUG_MSG( 4, ( " type=%u epoch=%u fragment_offset=%u", 3314 in[0], 3315 (unsigned) in[3] << 8 | in[4], 3316 (unsigned) in[19] << 16 | in[20] << 8 | in[21] ) ); 3317 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); 3318 } 3319 3320 sid_len = in[59]; 3321 if( 59 + 1 + sid_len + 1 > in_len ) 3322 { 3323 MBEDTLS_SSL_DEBUG_MSG( 4, ( "check cookie: sid_len=%u > %u", 3324 (unsigned) sid_len, 3325 (unsigned) in_len - 61 ) ); 3326 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); 3327 } 3328 MBEDTLS_SSL_DEBUG_BUF( 4, "sid received from network", 3329 in + 60, sid_len ); 3330 3331 cookie_len = in[60 + sid_len]; 3332 if( 59 + 1 + sid_len + 1 + cookie_len > in_len ) 3333 { 3334 MBEDTLS_SSL_DEBUG_MSG( 4, ( "check cookie: cookie_len=%u > %u", 3335 (unsigned) cookie_len, 3336 (unsigned) ( in_len - sid_len - 61 ) ) ); 3337 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); 3338 } 3339 3340 MBEDTLS_SSL_DEBUG_BUF( 4, "cookie received from network", 3341 in + sid_len + 61, cookie_len ); 3342 if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, 3343 in + sid_len + 61, cookie_len, 3344 cli_id, cli_id_len ) == 0 ) 3345 { 3346 MBEDTLS_SSL_DEBUG_MSG( 4, ( "check cookie: valid" ) ); 3347 return( 0 ); 3348 } 3349 3350 /* 3351 * If we get here, we've got an invalid cookie, let's prepare HVR. 3352 * 3353 * 0-0 ContentType type; copied 3354 * 1-2 ProtocolVersion version; copied 3355 * 3-4 uint16 epoch; copied 3356 * 5-10 uint48 sequence_number; copied 3357 * 11-12 uint16 length; olen - 13 3358 * 3359 * 13-13 HandshakeType msg_type; hello_verify_request 3360 * 14-16 uint24 length; olen - 25 3361 * 17-18 uint16 message_seq; copied 3362 * 19-21 uint24 fragment_offset; copied 3363 * 22-24 uint24 fragment_length; olen - 25 3364 * 3365 * 25-26 ProtocolVersion server_version; 0xfe 0xff 3366 * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie 3367 * 3368 * Minimum length is 28. 3369 */ 3370 if( buf_len < 28 ) 3371 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); 3372 3373 /* Copy most fields and adapt others */ 3374 memcpy( obuf, in, 25 ); 3375 obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; 3376 obuf[25] = 0xfe; 3377 obuf[26] = 0xff; 3378 3379 /* Generate and write actual cookie */ 3380 p = obuf + 28; 3381 if( ssl->conf->f_cookie_write( ssl->conf->p_cookie, 3382 &p, obuf + buf_len, 3383 cli_id, cli_id_len ) != 0 ) 3384 { 3385 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 3386 } 3387 3388 *olen = p - obuf; 3389 3390 /* Go back and fill length fields */ 3391 obuf[27] = (unsigned char)( *olen - 28 ); 3392 3393 obuf[14] = obuf[22] = MBEDTLS_BYTE_2( *olen - 25 ); 3394 obuf[15] = obuf[23] = MBEDTLS_BYTE_1( *olen - 25 ); 3395 obuf[16] = obuf[24] = MBEDTLS_BYTE_0( *olen - 25 ); 3396 3397 MBEDTLS_PUT_UINT16_BE( *olen - 13, obuf, 11 ); 3398 3399 return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); 3400 } 3401 3402 /* 3403 * Handle possible client reconnect with the same UDP quadruplet 3404 * (RFC 6347 Section 4.2.8). 3405 * 3406 * Called by ssl_parse_record_header() in case we receive an epoch 0 record 3407 * that looks like a ClientHello. 3408 * 3409 * - if the input looks like a ClientHello without cookies, 3410 * send back HelloVerifyRequest, then return 0 3411 * - if the input looks like a ClientHello with a valid cookie, 3412 * reset the session of the current context, and 3413 * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT 3414 * - if anything goes wrong, return a specific error code 3415 * 3416 * This function is called (through ssl_check_client_reconnect()) when an 3417 * unexpected record is found in ssl_get_next_record(), which will discard the 3418 * record if we return 0, and bubble up the return value otherwise (this 3419 * includes the case of MBEDTLS_ERR_SSL_CLIENT_RECONNECT and of unexpected 3420 * errors, and is the right thing to do in both cases). 3421 */ 3422 MBEDTLS_CHECK_RETURN_CRITICAL 3423 static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl ) 3424 { 3425 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 3426 size_t len; 3427 3428 if( ssl->conf->f_cookie_write == NULL || 3429 ssl->conf->f_cookie_check == NULL ) 3430 { 3431 /* If we can't use cookies to verify reachability of the peer, 3432 * drop the record. */ 3433 MBEDTLS_SSL_DEBUG_MSG( 1, ( "no cookie callbacks, " 3434 "can't check reconnect validity" ) ); 3435 return( 0 ); 3436 } 3437 3438 ret = mbedtls_ssl_check_dtls_clihlo_cookie( 3439 ssl, 3440 ssl->cli_id, ssl->cli_id_len, 3441 ssl->in_buf, ssl->in_left, 3442 ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len ); 3443 3444 MBEDTLS_SSL_DEBUG_RET( 2, "mbedtls_ssl_check_dtls_clihlo_cookie", ret ); 3445 3446 if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ) 3447 { 3448 int send_ret; 3449 MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) ); 3450 MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", 3451 ssl->out_buf, len ); 3452 /* Don't check write errors as we can't do anything here. 3453 * If the error is permanent we'll catch it later, 3454 * if it's not, then hopefully it'll work next time. */ 3455 send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len ); 3456 MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret ); 3457 (void) send_ret; 3458 3459 return( 0 ); 3460 } 3461 3462 if( ret == 0 ) 3463 { 3464 MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) ); 3465 if( ( ret = mbedtls_ssl_session_reset_int( ssl, 1 ) ) != 0 ) 3466 { 3467 MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret ); 3468 return( ret ); 3469 } 3470 3471 return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT ); 3472 } 3473 3474 return( ret ); 3475 } 3476 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ 3477 3478 MBEDTLS_CHECK_RETURN_CRITICAL 3479 static int ssl_check_record_type( uint8_t record_type ) 3480 { 3481 if( record_type != MBEDTLS_SSL_MSG_HANDSHAKE && 3482 record_type != MBEDTLS_SSL_MSG_ALERT && 3483 record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && 3484 record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA ) 3485 { 3486 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3487 } 3488 3489 return( 0 ); 3490 } 3491 3492 /* 3493 * ContentType type; 3494 * ProtocolVersion version; 3495 * uint16 epoch; // DTLS only 3496 * uint48 sequence_number; // DTLS only 3497 * uint16 length; 3498 * 3499 * Return 0 if header looks sane (and, for DTLS, the record is expected) 3500 * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad, 3501 * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected. 3502 * 3503 * With DTLS, mbedtls_ssl_read_record() will: 3504 * 1. proceed with the record if this function returns 0 3505 * 2. drop only the current record if this function returns UNEXPECTED_RECORD 3506 * 3. return CLIENT_RECONNECT if this function return that value 3507 * 4. drop the whole datagram if this function returns anything else. 3508 * Point 2 is needed when the peer is resending, and we have already received 3509 * the first record from a datagram but are still waiting for the others. 3510 */ 3511 MBEDTLS_CHECK_RETURN_CRITICAL 3512 static int ssl_parse_record_header( mbedtls_ssl_context const *ssl, 3513 unsigned char *buf, 3514 size_t len, 3515 mbedtls_record *rec ) 3516 { 3517 int major_ver, minor_ver; 3518 3519 size_t const rec_hdr_type_offset = 0; 3520 size_t const rec_hdr_type_len = 1; 3521 3522 size_t const rec_hdr_version_offset = rec_hdr_type_offset + 3523 rec_hdr_type_len; 3524 size_t const rec_hdr_version_len = 2; 3525 3526 size_t const rec_hdr_ctr_len = 8; 3527 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3528 uint32_t rec_epoch; 3529 size_t const rec_hdr_ctr_offset = rec_hdr_version_offset + 3530 rec_hdr_version_len; 3531 3532 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 3533 size_t const rec_hdr_cid_offset = rec_hdr_ctr_offset + 3534 rec_hdr_ctr_len; 3535 size_t rec_hdr_cid_len = 0; 3536 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 3537 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3538 3539 size_t rec_hdr_len_offset; /* To be determined */ 3540 size_t const rec_hdr_len_len = 2; 3541 3542 /* 3543 * Check minimum lengths for record header. 3544 */ 3545 3546 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3547 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 3548 { 3549 rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len; 3550 } 3551 else 3552 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3553 { 3554 rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len; 3555 } 3556 3557 if( len < rec_hdr_len_offset + rec_hdr_len_len ) 3558 { 3559 MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header of length %u", 3560 (unsigned) len, 3561 (unsigned)( rec_hdr_len_len + rec_hdr_len_len ) ) ); 3562 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3563 } 3564 3565 /* 3566 * Parse and validate record content type 3567 */ 3568 3569 rec->type = buf[ rec_hdr_type_offset ]; 3570 3571 /* Check record content type */ 3572 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 3573 rec->cid_len = 0; 3574 3575 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 3576 ssl->conf->cid_len != 0 && 3577 rec->type == MBEDTLS_SSL_MSG_CID ) 3578 { 3579 /* Shift pointers to account for record header including CID 3580 * struct { 3581 * ContentType special_type = tls12_cid; 3582 * ProtocolVersion version; 3583 * uint16 epoch; 3584 * uint48 sequence_number; 3585 * opaque cid[cid_length]; // Additional field compared to 3586 * // default DTLS record format 3587 * uint16 length; 3588 * opaque enc_content[DTLSCiphertext.length]; 3589 * } DTLSCiphertext; 3590 */ 3591 3592 /* So far, we only support static CID lengths 3593 * fixed in the configuration. */ 3594 rec_hdr_cid_len = ssl->conf->cid_len; 3595 rec_hdr_len_offset += rec_hdr_cid_len; 3596 3597 if( len < rec_hdr_len_offset + rec_hdr_len_len ) 3598 { 3599 MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header including CID, length %u", 3600 (unsigned) len, 3601 (unsigned)( rec_hdr_len_offset + rec_hdr_len_len ) ) ); 3602 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3603 } 3604 3605 /* configured CID len is guaranteed at most 255, see 3606 * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */ 3607 rec->cid_len = (uint8_t) rec_hdr_cid_len; 3608 memcpy( rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len ); 3609 } 3610 else 3611 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 3612 { 3613 if( ssl_check_record_type( rec->type ) ) 3614 { 3615 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type %u", 3616 (unsigned) rec->type ) ); 3617 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3618 } 3619 } 3620 3621 /* 3622 * Parse and validate record version 3623 */ 3624 rec->ver[0] = buf[ rec_hdr_version_offset + 0 ]; 3625 rec->ver[1] = buf[ rec_hdr_version_offset + 1 ]; 3626 mbedtls_ssl_read_version( &major_ver, &minor_ver, 3627 ssl->conf->transport, 3628 &rec->ver[0] ); 3629 3630 if( major_ver != ssl->major_ver ) 3631 { 3632 MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch: got %u, expected %u", 3633 (unsigned) major_ver, 3634 (unsigned) ssl->major_ver ) ); 3635 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3636 } 3637 3638 if( minor_ver > ssl->conf->max_minor_ver ) 3639 { 3640 MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch: got %u, expected max %u", 3641 (unsigned) minor_ver, 3642 (unsigned) ssl->conf->max_minor_ver ) ); 3643 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3644 } 3645 /* 3646 * Parse/Copy record sequence number. 3647 */ 3648 3649 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3650 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 3651 { 3652 /* Copy explicit record sequence number from input buffer. */ 3653 memcpy( &rec->ctr[0], buf + rec_hdr_ctr_offset, 3654 rec_hdr_ctr_len ); 3655 } 3656 else 3657 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3658 { 3659 /* Copy implicit record sequence number from SSL context structure. */ 3660 memcpy( &rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len ); 3661 } 3662 3663 /* 3664 * Parse record length. 3665 */ 3666 3667 rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len; 3668 rec->data_len = ( (size_t) buf[ rec_hdr_len_offset + 0 ] << 8 ) | 3669 ( (size_t) buf[ rec_hdr_len_offset + 1 ] << 0 ); 3670 MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", buf, rec->data_offset ); 3671 3672 MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %u, " 3673 "version = [%d:%d], msglen = %" MBEDTLS_PRINTF_SIZET, 3674 rec->type, 3675 major_ver, minor_ver, rec->data_len ) ); 3676 3677 rec->buf = buf; 3678 rec->buf_len = rec->data_offset + rec->data_len; 3679 3680 if( rec->data_len == 0 ) 3681 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3682 3683 /* 3684 * DTLS-related tests. 3685 * Check epoch before checking length constraint because 3686 * the latter varies with the epoch. E.g., if a ChangeCipherSpec 3687 * message gets duplicated before the corresponding Finished message, 3688 * the second ChangeCipherSpec should be discarded because it belongs 3689 * to an old epoch, but not because its length is shorter than 3690 * the minimum record length for packets using the new record transform. 3691 * Note that these two kinds of failures are handled differently, 3692 * as an unexpected record is silently skipped but an invalid 3693 * record leads to the entire datagram being dropped. 3694 */ 3695 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3696 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 3697 { 3698 rec_epoch = ( rec->ctr[0] << 8 ) | rec->ctr[1]; 3699 3700 /* Check that the datagram is large enough to contain a record 3701 * of the advertised length. */ 3702 if( len < rec->data_offset + rec->data_len ) 3703 { 3704 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Datagram of length %u too small to contain record of advertised length %u.", 3705 (unsigned) len, 3706 (unsigned)( rec->data_offset + rec->data_len ) ) ); 3707 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3708 } 3709 3710 /* Records from other, non-matching epochs are silently discarded. 3711 * (The case of same-port Client reconnects must be considered in 3712 * the caller). */ 3713 if( rec_epoch != ssl->in_epoch ) 3714 { 3715 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: " 3716 "expected %u, received %lu", 3717 ssl->in_epoch, (unsigned long) rec_epoch ) ); 3718 3719 /* Records from the next epoch are considered for buffering 3720 * (concretely: early Finished messages). */ 3721 if( rec_epoch == (unsigned) ssl->in_epoch + 1 ) 3722 { 3723 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) ); 3724 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); 3725 } 3726 3727 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); 3728 } 3729 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) 3730 /* For records from the correct epoch, check whether their 3731 * sequence number has been seen before. */ 3732 else if( mbedtls_ssl_dtls_record_replay_check( (mbedtls_ssl_context *) ssl, 3733 &rec->ctr[0] ) != 0 ) 3734 { 3735 MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) ); 3736 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); 3737 } 3738 #endif 3739 } 3740 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3741 3742 return( 0 ); 3743 } 3744 3745 3746 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) 3747 MBEDTLS_CHECK_RETURN_CRITICAL 3748 static int ssl_check_client_reconnect( mbedtls_ssl_context *ssl ) 3749 { 3750 unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1]; 3751 3752 /* 3753 * Check for an epoch 0 ClientHello. We can't use in_msg here to 3754 * access the first byte of record content (handshake type), as we 3755 * have an active transform (possibly iv_len != 0), so use the 3756 * fact that the record header len is 13 instead. 3757 */ 3758 if( rec_epoch == 0 && 3759 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && 3760 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && 3761 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && 3762 ssl->in_left > 13 && 3763 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO ) 3764 { 3765 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect " 3766 "from the same port" ) ); 3767 return( ssl_handle_possible_reconnect( ssl ) ); 3768 } 3769 3770 return( 0 ); 3771 } 3772 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ 3773 3774 /* 3775 * If applicable, decrypt record content 3776 */ 3777 MBEDTLS_CHECK_RETURN_CRITICAL 3778 static int ssl_prepare_record_content( mbedtls_ssl_context *ssl, 3779 mbedtls_record *rec ) 3780 { 3781 int ret, done = 0; 3782 3783 MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network", 3784 rec->buf, rec->buf_len ); 3785 3786 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) 3787 if( mbedtls_ssl_hw_record_read != NULL ) 3788 { 3789 MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) ); 3790 3791 ret = mbedtls_ssl_hw_record_read( ssl ); 3792 if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) 3793 { 3794 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret ); 3795 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); 3796 } 3797 3798 if( ret == 0 ) 3799 done = 1; 3800 } 3801 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ 3802 if( !done && ssl->transform_in != NULL ) 3803 { 3804 unsigned char const old_msg_type = rec->type; 3805 3806 if( ( ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, 3807 rec ) ) != 0 ) 3808 { 3809 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret ); 3810 3811 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 3812 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID && 3813 ssl->conf->ignore_unexpected_cid 3814 == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE ) 3815 { 3816 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ignoring unexpected CID" ) ); 3817 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING; 3818 } 3819 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 3820 3821 return( ret ); 3822 } 3823 3824 if( old_msg_type != rec->type ) 3825 { 3826 MBEDTLS_SSL_DEBUG_MSG( 4, ( "record type after decrypt (before %d): %d", 3827 old_msg_type, rec->type ) ); 3828 } 3829 3830 MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt", 3831 rec->buf + rec->data_offset, rec->data_len ); 3832 3833 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 3834 /* We have already checked the record content type 3835 * in ssl_parse_record_header(), failing or silently 3836 * dropping the record in the case of an unknown type. 3837 * 3838 * Since with the use of CIDs, the record content type 3839 * might change during decryption, re-check the record 3840 * content type, but treat a failure as fatal this time. */ 3841 if( ssl_check_record_type( rec->type ) ) 3842 { 3843 MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); 3844 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3845 } 3846 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 3847 3848 if( rec->data_len == 0 ) 3849 { 3850 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) 3851 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 3852 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA ) 3853 { 3854 /* TLS v1.2 explicitly disallows zero-length messages which are not application data */ 3855 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) ); 3856 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3857 } 3858 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ 3859 3860 ssl->nb_zero++; 3861 3862 /* 3863 * Three or more empty messages may be a DoS attack 3864 * (excessive CPU consumption). 3865 */ 3866 if( ssl->nb_zero > 3 ) 3867 { 3868 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty " 3869 "messages, possible DoS attack" ) ); 3870 /* Treat the records as if they were not properly authenticated, 3871 * thereby failing the connection if we see more than allowed 3872 * by the configured bad MAC threshold. */ 3873 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 3874 } 3875 } 3876 else 3877 ssl->nb_zero = 0; 3878 3879 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3880 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 3881 { 3882 ; /* in_ctr read from peer, not maintained internally */ 3883 } 3884 else 3885 #endif 3886 { 3887 unsigned i; 3888 for( i = 8; i > mbedtls_ssl_ep_len( ssl ); i-- ) 3889 if( ++ssl->in_ctr[i - 1] != 0 ) 3890 break; 3891 3892 /* The loop goes to its end iff the counter is wrapping */ 3893 if( i == mbedtls_ssl_ep_len( ssl ) ) 3894 { 3895 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) ); 3896 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); 3897 } 3898 } 3899 3900 } 3901 3902 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) 3903 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 3904 { 3905 mbedtls_ssl_dtls_replay_update( ssl ); 3906 } 3907 #endif 3908 3909 /* Check actual (decrypted) record content length against 3910 * configured maximum. */ 3911 if( rec->data_len > MBEDTLS_SSL_IN_CONTENT_LEN ) 3912 { 3913 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); 3914 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 3915 } 3916 3917 return( 0 ); 3918 } 3919 3920 /* 3921 * Read a record. 3922 * 3923 * Silently ignore non-fatal alert (and for DTLS, invalid records as well, 3924 * RFC 6347 4.1.2.7) and continue reading until a valid record is found. 3925 * 3926 */ 3927 3928 /* Helper functions for mbedtls_ssl_read_record(). */ 3929 MBEDTLS_CHECK_RETURN_CRITICAL 3930 static int ssl_consume_current_message( mbedtls_ssl_context *ssl ); 3931 MBEDTLS_CHECK_RETURN_CRITICAL 3932 static int ssl_get_next_record( mbedtls_ssl_context *ssl ); 3933 MBEDTLS_CHECK_RETURN_CRITICAL 3934 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ); 3935 3936 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl, 3937 unsigned update_hs_digest ) 3938 { 3939 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 3940 3941 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) ); 3942 3943 if( ssl->keep_current_message == 0 ) 3944 { 3945 do { 3946 3947 ret = ssl_consume_current_message( ssl ); 3948 if( ret != 0 ) 3949 return( ret ); 3950 3951 if( ssl_record_is_in_progress( ssl ) == 0 ) 3952 { 3953 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3954 int have_buffered = 0; 3955 3956 /* We only check for buffered messages if the 3957 * current datagram is fully consumed. */ 3958 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 3959 ssl_next_record_is_in_datagram( ssl ) == 0 ) 3960 { 3961 if( ssl_load_buffered_message( ssl ) == 0 ) 3962 have_buffered = 1; 3963 } 3964 3965 if( have_buffered == 0 ) 3966 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3967 { 3968 ret = ssl_get_next_record( ssl ); 3969 if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ) 3970 continue; 3971 3972 if( ret != 0 ) 3973 { 3974 MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret ); 3975 return( ret ); 3976 } 3977 } 3978 } 3979 3980 ret = mbedtls_ssl_handle_message_type( ssl ); 3981 3982 #if defined(MBEDTLS_SSL_PROTO_DTLS) 3983 if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) 3984 { 3985 /* Buffer future message */ 3986 ret = ssl_buffer_message( ssl ); 3987 if( ret != 0 ) 3988 return( ret ); 3989 3990 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING; 3991 } 3992 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 3993 3994 } while( MBEDTLS_ERR_SSL_NON_FATAL == ret || 3995 MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret ); 3996 3997 if( 0 != ret ) 3998 { 3999 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret ); 4000 return( ret ); 4001 } 4002 4003 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && 4004 update_hs_digest == 1 ) 4005 { 4006 mbedtls_ssl_update_handshake_status( ssl ); 4007 } 4008 } 4009 else 4010 { 4011 MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) ); 4012 ssl->keep_current_message = 0; 4013 } 4014 4015 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) ); 4016 4017 return( 0 ); 4018 } 4019 4020 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4021 MBEDTLS_CHECK_RETURN_CRITICAL 4022 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl ) 4023 { 4024 if( ssl->in_left > ssl->next_record_offset ) 4025 return( 1 ); 4026 4027 return( 0 ); 4028 } 4029 4030 MBEDTLS_CHECK_RETURN_CRITICAL 4031 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl ) 4032 { 4033 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 4034 mbedtls_ssl_hs_buffer * hs_buf; 4035 int ret = 0; 4036 4037 if( hs == NULL ) 4038 return( -1 ); 4039 4040 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) ); 4041 4042 if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC || 4043 ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) 4044 { 4045 /* Check if we have seen a ChangeCipherSpec before. 4046 * If yes, synthesize a CCS record. */ 4047 if( !hs->buffering.seen_ccs ) 4048 { 4049 MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) ); 4050 ret = -1; 4051 goto exit; 4052 } 4053 4054 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) ); 4055 ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; 4056 ssl->in_msglen = 1; 4057 ssl->in_msg[0] = 1; 4058 4059 /* As long as they are equal, the exact value doesn't matter. */ 4060 ssl->in_left = 0; 4061 ssl->next_record_offset = 0; 4062 4063 hs->buffering.seen_ccs = 0; 4064 goto exit; 4065 } 4066 4067 #if defined(MBEDTLS_DEBUG_C) 4068 /* Debug only */ 4069 { 4070 unsigned offset; 4071 for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ ) 4072 { 4073 hs_buf = &hs->buffering.hs[offset]; 4074 if( hs_buf->is_valid == 1 ) 4075 { 4076 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.", 4077 hs->in_msg_seq + offset, 4078 hs_buf->is_complete ? "fully" : "partially" ) ); 4079 } 4080 } 4081 } 4082 #endif /* MBEDTLS_DEBUG_C */ 4083 4084 /* Check if we have buffered and/or fully reassembled the 4085 * next handshake message. */ 4086 hs_buf = &hs->buffering.hs[0]; 4087 if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) ) 4088 { 4089 /* Synthesize a record containing the buffered HS message. */ 4090 size_t msg_len = ( hs_buf->data[1] << 16 ) | 4091 ( hs_buf->data[2] << 8 ) | 4092 hs_buf->data[3]; 4093 4094 /* Double-check that we haven't accidentally buffered 4095 * a message that doesn't fit into the input buffer. */ 4096 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN ) 4097 { 4098 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 4099 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 4100 } 4101 4102 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) ); 4103 MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)", 4104 hs_buf->data, msg_len + 12 ); 4105 4106 ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; 4107 ssl->in_hslen = msg_len + 12; 4108 ssl->in_msglen = msg_len + 12; 4109 memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen ); 4110 4111 ret = 0; 4112 goto exit; 4113 } 4114 else 4115 { 4116 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered", 4117 hs->in_msg_seq ) ); 4118 } 4119 4120 ret = -1; 4121 4122 exit: 4123 4124 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) ); 4125 return( ret ); 4126 } 4127 4128 MBEDTLS_CHECK_RETURN_CRITICAL 4129 static int ssl_buffer_make_space( mbedtls_ssl_context *ssl, 4130 size_t desired ) 4131 { 4132 int offset; 4133 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 4134 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available", 4135 (unsigned) desired ) ); 4136 4137 /* Get rid of future records epoch first, if such exist. */ 4138 ssl_free_buffered_record( ssl ); 4139 4140 /* Check if we have enough space available now. */ 4141 if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - 4142 hs->buffering.total_bytes_buffered ) ) 4143 { 4144 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) ); 4145 return( 0 ); 4146 } 4147 4148 /* We don't have enough space to buffer the next expected handshake 4149 * message. Remove buffers used for future messages to gain space, 4150 * starting with the most distant one. */ 4151 for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1; 4152 offset >= 0; offset-- ) 4153 { 4154 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message", 4155 offset ) ); 4156 4157 ssl_buffering_free_slot( ssl, (uint8_t) offset ); 4158 4159 /* Check if we have enough space available now. */ 4160 if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - 4161 hs->buffering.total_bytes_buffered ) ) 4162 { 4163 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) ); 4164 return( 0 ); 4165 } 4166 } 4167 4168 return( -1 ); 4169 } 4170 4171 MBEDTLS_CHECK_RETURN_CRITICAL 4172 static int ssl_buffer_message( mbedtls_ssl_context *ssl ) 4173 { 4174 int ret = 0; 4175 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 4176 4177 if( hs == NULL ) 4178 return( 0 ); 4179 4180 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) ); 4181 4182 switch( ssl->in_msgtype ) 4183 { 4184 case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC: 4185 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) ); 4186 4187 hs->buffering.seen_ccs = 1; 4188 break; 4189 4190 case MBEDTLS_SSL_MSG_HANDSHAKE: 4191 { 4192 unsigned recv_msg_seq_offset; 4193 unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; 4194 mbedtls_ssl_hs_buffer *hs_buf; 4195 size_t msg_len = ssl->in_hslen - 12; 4196 4197 /* We should never receive an old handshake 4198 * message - double-check nonetheless. */ 4199 if( recv_msg_seq < ssl->handshake->in_msg_seq ) 4200 { 4201 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 4202 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 4203 } 4204 4205 recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq; 4206 if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS ) 4207 { 4208 /* Silently ignore -- message too far in the future */ 4209 MBEDTLS_SSL_DEBUG_MSG( 2, 4210 ( "Ignore future HS message with sequence number %u, " 4211 "buffering window %u - %u", 4212 recv_msg_seq, ssl->handshake->in_msg_seq, 4213 ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) ); 4214 4215 goto exit; 4216 } 4217 4218 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ", 4219 recv_msg_seq, recv_msg_seq_offset ) ); 4220 4221 hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ]; 4222 4223 /* Check if the buffering for this seq nr has already commenced. */ 4224 if( !hs_buf->is_valid ) 4225 { 4226 size_t reassembly_buf_sz; 4227 4228 hs_buf->is_fragmented = 4229 ( ssl_hs_is_proper_fragment( ssl ) == 1 ); 4230 4231 /* We copy the message back into the input buffer 4232 * after reassembly, so check that it's not too large. 4233 * This is an implementation-specific limitation 4234 * and not one from the standard, hence it is not 4235 * checked in ssl_check_hs_header(). */ 4236 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN ) 4237 { 4238 /* Ignore message */ 4239 goto exit; 4240 } 4241 4242 /* Check if we have enough space to buffer the message. */ 4243 if( hs->buffering.total_bytes_buffered > 4244 MBEDTLS_SSL_DTLS_MAX_BUFFERING ) 4245 { 4246 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 4247 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 4248 } 4249 4250 reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len, 4251 hs_buf->is_fragmented ); 4252 4253 if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - 4254 hs->buffering.total_bytes_buffered ) ) 4255 { 4256 if( recv_msg_seq_offset > 0 ) 4257 { 4258 /* If we can't buffer a future message because 4259 * of space limitations -- ignore. */ 4260 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %" MBEDTLS_PRINTF_SIZET 4261 " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET 4262 " (already %" MBEDTLS_PRINTF_SIZET 4263 " bytes buffered) -- ignore\n", 4264 msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, 4265 hs->buffering.total_bytes_buffered ) ); 4266 goto exit; 4267 } 4268 else 4269 { 4270 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %" MBEDTLS_PRINTF_SIZET 4271 " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET 4272 " (already %" MBEDTLS_PRINTF_SIZET 4273 " bytes buffered) -- attempt to make space by freeing buffered future messages\n", 4274 msg_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, 4275 hs->buffering.total_bytes_buffered ) ); 4276 } 4277 4278 if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 ) 4279 { 4280 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %" MBEDTLS_PRINTF_SIZET 4281 " (%" MBEDTLS_PRINTF_SIZET " with bitmap) would exceed" 4282 " the compile-time limit %" MBEDTLS_PRINTF_SIZET 4283 " (already %" MBEDTLS_PRINTF_SIZET 4284 " bytes buffered) -- fail\n", 4285 msg_len, 4286 reassembly_buf_sz, 4287 (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, 4288 hs->buffering.total_bytes_buffered ) ); 4289 ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL; 4290 goto exit; 4291 } 4292 } 4293 4294 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %" MBEDTLS_PRINTF_SIZET, 4295 msg_len ) ); 4296 4297 hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz ); 4298 if( hs_buf->data == NULL ) 4299 { 4300 ret = MBEDTLS_ERR_SSL_ALLOC_FAILED; 4301 goto exit; 4302 } 4303 hs_buf->data_len = reassembly_buf_sz; 4304 4305 /* Prepare final header: copy msg_type, length and message_seq, 4306 * then add standardised fragment_offset and fragment_length */ 4307 memcpy( hs_buf->data, ssl->in_msg, 6 ); 4308 memset( hs_buf->data + 6, 0, 3 ); 4309 memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 ); 4310 4311 hs_buf->is_valid = 1; 4312 4313 hs->buffering.total_bytes_buffered += reassembly_buf_sz; 4314 } 4315 else 4316 { 4317 /* Make sure msg_type and length are consistent */ 4318 if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 ) 4319 { 4320 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) ); 4321 /* Ignore */ 4322 goto exit; 4323 } 4324 } 4325 4326 if( !hs_buf->is_complete ) 4327 { 4328 size_t frag_len, frag_off; 4329 unsigned char * const msg = hs_buf->data + 12; 4330 4331 /* 4332 * Check and copy current fragment 4333 */ 4334 4335 /* Validation of header fields already done in 4336 * mbedtls_ssl_prepare_handshake_record(). */ 4337 frag_off = ssl_get_hs_frag_off( ssl ); 4338 frag_len = ssl_get_hs_frag_len( ssl ); 4339 4340 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %" MBEDTLS_PRINTF_SIZET 4341 ", length = %" MBEDTLS_PRINTF_SIZET, 4342 frag_off, frag_len ) ); 4343 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len ); 4344 4345 if( hs_buf->is_fragmented ) 4346 { 4347 unsigned char * const bitmask = msg + msg_len; 4348 ssl_bitmask_set( bitmask, frag_off, frag_len ); 4349 hs_buf->is_complete = ( ssl_bitmask_check( bitmask, 4350 msg_len ) == 0 ); 4351 } 4352 else 4353 { 4354 hs_buf->is_complete = 1; 4355 } 4356 4357 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete", 4358 hs_buf->is_complete ? "" : "not yet " ) ); 4359 } 4360 4361 break; 4362 } 4363 4364 default: 4365 /* We don't buffer other types of messages. */ 4366 break; 4367 } 4368 4369 exit: 4370 4371 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) ); 4372 return( ret ); 4373 } 4374 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 4375 4376 MBEDTLS_CHECK_RETURN_CRITICAL 4377 static int ssl_consume_current_message( mbedtls_ssl_context *ssl ) 4378 { 4379 /* 4380 * Consume last content-layer message and potentially 4381 * update in_msglen which keeps track of the contents' 4382 * consumption state. 4383 * 4384 * (1) Handshake messages: 4385 * Remove last handshake message, move content 4386 * and adapt in_msglen. 4387 * 4388 * (2) Alert messages: 4389 * Consume whole record content, in_msglen = 0. 4390 * 4391 * (3) Change cipher spec: 4392 * Consume whole record content, in_msglen = 0. 4393 * 4394 * (4) Application data: 4395 * Don't do anything - the record layer provides 4396 * the application data as a stream transport 4397 * and consumes through mbedtls_ssl_read only. 4398 * 4399 */ 4400 4401 /* Case (1): Handshake messages */ 4402 if( ssl->in_hslen != 0 ) 4403 { 4404 /* Hard assertion to be sure that no application data 4405 * is in flight, as corrupting ssl->in_msglen during 4406 * ssl->in_offt != NULL is fatal. */ 4407 if( ssl->in_offt != NULL ) 4408 { 4409 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 4410 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 4411 } 4412 4413 /* 4414 * Get next Handshake message in the current record 4415 */ 4416 4417 /* Notes: 4418 * (1) in_hslen is not necessarily the size of the 4419 * current handshake content: If DTLS handshake 4420 * fragmentation is used, that's the fragment 4421 * size instead. Using the total handshake message 4422 * size here is faulty and should be changed at 4423 * some point. 4424 * (2) While it doesn't seem to cause problems, one 4425 * has to be very careful not to assume that in_hslen 4426 * is always <= in_msglen in a sensible communication. 4427 * Again, it's wrong for DTLS handshake fragmentation. 4428 * The following check is therefore mandatory, and 4429 * should not be treated as a silently corrected assertion. 4430 * Additionally, ssl->in_hslen might be arbitrarily out of 4431 * bounds after handling a DTLS message with an unexpected 4432 * sequence number, see mbedtls_ssl_prepare_handshake_record. 4433 */ 4434 if( ssl->in_hslen < ssl->in_msglen ) 4435 { 4436 ssl->in_msglen -= ssl->in_hslen; 4437 memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen, 4438 ssl->in_msglen ); 4439 4440 MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record", 4441 ssl->in_msg, ssl->in_msglen ); 4442 } 4443 else 4444 { 4445 ssl->in_msglen = 0; 4446 } 4447 4448 ssl->in_hslen = 0; 4449 } 4450 /* Case (4): Application data */ 4451 else if( ssl->in_offt != NULL ) 4452 { 4453 return( 0 ); 4454 } 4455 /* Everything else (CCS & Alerts) */ 4456 else 4457 { 4458 ssl->in_msglen = 0; 4459 } 4460 4461 return( 0 ); 4462 } 4463 4464 MBEDTLS_CHECK_RETURN_CRITICAL 4465 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl ) 4466 { 4467 if( ssl->in_msglen > 0 ) 4468 return( 1 ); 4469 4470 return( 0 ); 4471 } 4472 4473 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4474 4475 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl ) 4476 { 4477 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 4478 if( hs == NULL ) 4479 return; 4480 4481 if( hs->buffering.future_record.data != NULL ) 4482 { 4483 hs->buffering.total_bytes_buffered -= 4484 hs->buffering.future_record.len; 4485 4486 mbedtls_free( hs->buffering.future_record.data ); 4487 hs->buffering.future_record.data = NULL; 4488 } 4489 } 4490 4491 MBEDTLS_CHECK_RETURN_CRITICAL 4492 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl ) 4493 { 4494 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 4495 unsigned char * rec; 4496 size_t rec_len; 4497 unsigned rec_epoch; 4498 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) 4499 size_t in_buf_len = ssl->in_buf_len; 4500 #else 4501 size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN; 4502 #endif 4503 if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 4504 return( 0 ); 4505 4506 if( hs == NULL ) 4507 return( 0 ); 4508 4509 rec = hs->buffering.future_record.data; 4510 rec_len = hs->buffering.future_record.len; 4511 rec_epoch = hs->buffering.future_record.epoch; 4512 4513 if( rec == NULL ) 4514 return( 0 ); 4515 4516 /* Only consider loading future records if the 4517 * input buffer is empty. */ 4518 if( ssl_next_record_is_in_datagram( ssl ) == 1 ) 4519 return( 0 ); 4520 4521 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) ); 4522 4523 if( rec_epoch != ssl->in_epoch ) 4524 { 4525 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) ); 4526 goto exit; 4527 } 4528 4529 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) ); 4530 4531 /* Double-check that the record is not too large */ 4532 if( rec_len > in_buf_len - (size_t)( ssl->in_hdr - ssl->in_buf ) ) 4533 { 4534 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 4535 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 4536 } 4537 4538 memcpy( ssl->in_hdr, rec, rec_len ); 4539 ssl->in_left = rec_len; 4540 ssl->next_record_offset = 0; 4541 4542 ssl_free_buffered_record( ssl ); 4543 4544 exit: 4545 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) ); 4546 return( 0 ); 4547 } 4548 4549 MBEDTLS_CHECK_RETURN_CRITICAL 4550 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl, 4551 mbedtls_record const *rec ) 4552 { 4553 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 4554 4555 /* Don't buffer future records outside handshakes. */ 4556 if( hs == NULL ) 4557 return( 0 ); 4558 4559 /* Only buffer handshake records (we are only interested 4560 * in Finished messages). */ 4561 if( rec->type != MBEDTLS_SSL_MSG_HANDSHAKE ) 4562 return( 0 ); 4563 4564 /* Don't buffer more than one future epoch record. */ 4565 if( hs->buffering.future_record.data != NULL ) 4566 return( 0 ); 4567 4568 /* Don't buffer record if there's not enough buffering space remaining. */ 4569 if( rec->buf_len > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING - 4570 hs->buffering.total_bytes_buffered ) ) 4571 { 4572 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %" MBEDTLS_PRINTF_SIZET 4573 " would exceed the compile-time limit %" MBEDTLS_PRINTF_SIZET 4574 " (already %" MBEDTLS_PRINTF_SIZET 4575 " bytes buffered) -- ignore\n", 4576 rec->buf_len, (size_t) MBEDTLS_SSL_DTLS_MAX_BUFFERING, 4577 hs->buffering.total_bytes_buffered ) ); 4578 return( 0 ); 4579 } 4580 4581 /* Buffer record */ 4582 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u", 4583 ssl->in_epoch + 1U ) ); 4584 MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", rec->buf, rec->buf_len ); 4585 4586 /* ssl_parse_record_header() only considers records 4587 * of the next epoch as candidates for buffering. */ 4588 hs->buffering.future_record.epoch = ssl->in_epoch + 1; 4589 hs->buffering.future_record.len = rec->buf_len; 4590 4591 hs->buffering.future_record.data = 4592 mbedtls_calloc( 1, hs->buffering.future_record.len ); 4593 if( hs->buffering.future_record.data == NULL ) 4594 { 4595 /* If we run out of RAM trying to buffer a 4596 * record from the next epoch, just ignore. */ 4597 return( 0 ); 4598 } 4599 4600 memcpy( hs->buffering.future_record.data, rec->buf, rec->buf_len ); 4601 4602 hs->buffering.total_bytes_buffered += rec->buf_len; 4603 return( 0 ); 4604 } 4605 4606 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 4607 4608 MBEDTLS_CHECK_RETURN_CRITICAL 4609 static int ssl_get_next_record( mbedtls_ssl_context *ssl ) 4610 { 4611 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 4612 mbedtls_record rec; 4613 4614 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4615 /* We might have buffered a future record; if so, 4616 * and if the epoch matches now, load it. 4617 * On success, this call will set ssl->in_left to 4618 * the length of the buffered record, so that 4619 * the calls to ssl_fetch_input() below will 4620 * essentially be no-ops. */ 4621 ret = ssl_load_buffered_record( ssl ); 4622 if( ret != 0 ) 4623 return( ret ); 4624 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 4625 4626 /* Ensure that we have enough space available for the default form 4627 * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS, 4628 * with no space for CIDs counted in). */ 4629 ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) ); 4630 if( ret != 0 ) 4631 { 4632 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); 4633 return( ret ); 4634 } 4635 4636 ret = ssl_parse_record_header( ssl, ssl->in_hdr, ssl->in_left, &rec ); 4637 if( ret != 0 ) 4638 { 4639 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4640 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 4641 { 4642 if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE ) 4643 { 4644 ret = ssl_buffer_future_record( ssl, &rec ); 4645 if( ret != 0 ) 4646 return( ret ); 4647 4648 /* Fall through to handling of unexpected records */ 4649 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; 4650 } 4651 4652 if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ) 4653 { 4654 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) 4655 /* Reset in pointers to default state for TLS/DTLS records, 4656 * assuming no CID and no offset between record content and 4657 * record plaintext. */ 4658 mbedtls_ssl_update_in_pointers( ssl ); 4659 4660 /* Setup internal message pointers from record structure. */ 4661 ssl->in_msgtype = rec.type; 4662 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 4663 ssl->in_len = ssl->in_cid + rec.cid_len; 4664 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 4665 ssl->in_iv = ssl->in_msg = ssl->in_len + 2; 4666 ssl->in_msglen = rec.data_len; 4667 4668 ret = ssl_check_client_reconnect( ssl ); 4669 MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_client_reconnect", ret ); 4670 if( ret != 0 ) 4671 return( ret ); 4672 #endif 4673 4674 /* Skip unexpected record (but not whole datagram) */ 4675 ssl->next_record_offset = rec.buf_len; 4676 4677 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record " 4678 "(header)" ) ); 4679 } 4680 else 4681 { 4682 /* Skip invalid record and the rest of the datagram */ 4683 ssl->next_record_offset = 0; 4684 ssl->in_left = 0; 4685 4686 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record " 4687 "(header)" ) ); 4688 } 4689 4690 /* Get next record */ 4691 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); 4692 } 4693 else 4694 #endif 4695 { 4696 return( ret ); 4697 } 4698 } 4699 4700 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4701 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 4702 { 4703 /* Remember offset of next record within datagram. */ 4704 ssl->next_record_offset = rec.buf_len; 4705 if( ssl->next_record_offset < ssl->in_left ) 4706 { 4707 MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) ); 4708 } 4709 } 4710 else 4711 #endif 4712 { 4713 /* 4714 * Fetch record contents from underlying transport. 4715 */ 4716 ret = mbedtls_ssl_fetch_input( ssl, rec.buf_len ); 4717 if( ret != 0 ) 4718 { 4719 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); 4720 return( ret ); 4721 } 4722 4723 ssl->in_left = 0; 4724 } 4725 4726 /* 4727 * Decrypt record contents. 4728 */ 4729 4730 if( ( ret = ssl_prepare_record_content( ssl, &rec ) ) != 0 ) 4731 { 4732 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4733 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 4734 { 4735 /* Silently discard invalid records */ 4736 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) 4737 { 4738 /* Except when waiting for Finished as a bad mac here 4739 * probably means something went wrong in the handshake 4740 * (eg wrong psk used, mitm downgrade attempt, etc.) */ 4741 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED || 4742 ssl->state == MBEDTLS_SSL_SERVER_FINISHED ) 4743 { 4744 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) 4745 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) 4746 { 4747 mbedtls_ssl_send_alert_message( ssl, 4748 MBEDTLS_SSL_ALERT_LEVEL_FATAL, 4749 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); 4750 } 4751 #endif 4752 return( ret ); 4753 } 4754 4755 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) 4756 if( ssl->conf->badmac_limit != 0 && 4757 ++ssl->badmac_seen >= ssl->conf->badmac_limit ) 4758 { 4759 MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) ); 4760 return( MBEDTLS_ERR_SSL_INVALID_MAC ); 4761 } 4762 #endif 4763 4764 /* As above, invalid records cause 4765 * dismissal of the whole datagram. */ 4766 4767 ssl->next_record_offset = 0; 4768 ssl->in_left = 0; 4769 4770 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) ); 4771 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING ); 4772 } 4773 4774 return( ret ); 4775 } 4776 else 4777 #endif 4778 { 4779 /* Error out (and send alert) on invalid records */ 4780 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) 4781 if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) 4782 { 4783 mbedtls_ssl_send_alert_message( ssl, 4784 MBEDTLS_SSL_ALERT_LEVEL_FATAL, 4785 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); 4786 } 4787 #endif 4788 return( ret ); 4789 } 4790 } 4791 4792 4793 /* Reset in pointers to default state for TLS/DTLS records, 4794 * assuming no CID and no offset between record content and 4795 * record plaintext. */ 4796 mbedtls_ssl_update_in_pointers( ssl ); 4797 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 4798 ssl->in_len = ssl->in_cid + rec.cid_len; 4799 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 4800 ssl->in_iv = ssl->in_len + 2; 4801 4802 /* The record content type may change during decryption, 4803 * so re-read it. */ 4804 ssl->in_msgtype = rec.type; 4805 /* Also update the input buffer, because unfortunately 4806 * the server-side ssl_parse_client_hello() reparses the 4807 * record header when receiving a ClientHello initiating 4808 * a renegotiation. */ 4809 ssl->in_hdr[0] = rec.type; 4810 ssl->in_msg = rec.buf + rec.data_offset; 4811 ssl->in_msglen = rec.data_len; 4812 MBEDTLS_PUT_UINT16_BE( rec.data_len, ssl->in_len, 0 ); 4813 4814 #if defined(MBEDTLS_ZLIB_SUPPORT) 4815 if( ssl->transform_in != NULL && 4816 ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) 4817 { 4818 if( ( ret = ssl_decompress_buf( ssl ) ) != 0 ) 4819 { 4820 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret ); 4821 return( ret ); 4822 } 4823 4824 /* Check actual (decompress) record content length against 4825 * configured maximum. */ 4826 if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN ) 4827 { 4828 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); 4829 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 4830 } 4831 } 4832 #endif /* MBEDTLS_ZLIB_SUPPORT */ 4833 4834 return( 0 ); 4835 } 4836 4837 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) 4838 { 4839 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 4840 4841 /* 4842 * Handle particular types of records 4843 */ 4844 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) 4845 { 4846 if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 ) 4847 { 4848 return( ret ); 4849 } 4850 } 4851 4852 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) 4853 { 4854 if( ssl->in_msglen != 1 ) 4855 { 4856 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %" MBEDTLS_PRINTF_SIZET, 4857 ssl->in_msglen ) ); 4858 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 4859 } 4860 4861 if( ssl->in_msg[0] != 1 ) 4862 { 4863 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x", 4864 ssl->in_msg[0] ) ); 4865 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 4866 } 4867 4868 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4869 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 4870 ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && 4871 ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) 4872 { 4873 if( ssl->handshake == NULL ) 4874 { 4875 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) ); 4876 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); 4877 } 4878 4879 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) ); 4880 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE ); 4881 } 4882 #endif 4883 } 4884 4885 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) 4886 { 4887 if( ssl->in_msglen != 2 ) 4888 { 4889 /* Note: Standard allows for more than one 2 byte alert 4890 to be packed in a single message, but Mbed TLS doesn't 4891 currently support this. */ 4892 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %" MBEDTLS_PRINTF_SIZET, 4893 ssl->in_msglen ) ); 4894 return( MBEDTLS_ERR_SSL_INVALID_RECORD ); 4895 } 4896 4897 MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%u:%u]", 4898 ssl->in_msg[0], ssl->in_msg[1] ) ); 4899 4900 /* 4901 * Ignore non-fatal alerts, except close_notify and no_renegotiation 4902 */ 4903 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL ) 4904 { 4905 MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)", 4906 ssl->in_msg[1] ) ); 4907 return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE ); 4908 } 4909 4910 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && 4911 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) 4912 { 4913 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) ); 4914 return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ); 4915 } 4916 4917 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED) 4918 if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && 4919 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) 4920 { 4921 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) ); 4922 /* Will be handled when trying to parse ServerHello */ 4923 return( 0 ); 4924 } 4925 #endif 4926 4927 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C) 4928 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && 4929 ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && 4930 ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && 4931 ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) 4932 { 4933 MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); 4934 /* Will be handled in mbedtls_ssl_parse_certificate() */ 4935 return( 0 ); 4936 } 4937 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ 4938 4939 /* Silently ignore: fetch new message */ 4940 return MBEDTLS_ERR_SSL_NON_FATAL; 4941 } 4942 4943 #if defined(MBEDTLS_SSL_PROTO_DTLS) 4944 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 4945 { 4946 /* Drop unexpected ApplicationData records, 4947 * except at the beginning of renegotiations */ 4948 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && 4949 ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER 4950 #if defined(MBEDTLS_SSL_RENEGOTIATION) 4951 && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && 4952 ssl->state == MBEDTLS_SSL_SERVER_HELLO ) 4953 #endif 4954 ) 4955 { 4956 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); 4957 return( MBEDTLS_ERR_SSL_NON_FATAL ); 4958 } 4959 4960 if( ssl->handshake != NULL && 4961 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) 4962 { 4963 mbedtls_ssl_handshake_wrapup_free_hs_transform( ssl ); 4964 } 4965 } 4966 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 4967 4968 return( 0 ); 4969 } 4970 4971 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ) 4972 { 4973 return( mbedtls_ssl_send_alert_message( ssl, 4974 MBEDTLS_SSL_ALERT_LEVEL_FATAL, 4975 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ); 4976 } 4977 4978 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, 4979 unsigned char level, 4980 unsigned char message ) 4981 { 4982 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 4983 4984 if( ssl == NULL || ssl->conf == NULL ) 4985 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 4986 4987 if( ssl->out_left != 0 ) 4988 return( mbedtls_ssl_flush_output( ssl ) ); 4989 4990 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) ); 4991 MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message )); 4992 4993 ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; 4994 ssl->out_msglen = 2; 4995 ssl->out_msg[0] = level; 4996 ssl->out_msg[1] = message; 4997 4998 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) 4999 { 5000 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); 5001 return( ret ); 5002 } 5003 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) ); 5004 5005 return( 0 ); 5006 } 5007 5008 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl ) 5009 { 5010 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 5011 5012 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) ); 5013 5014 ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; 5015 ssl->out_msglen = 1; 5016 ssl->out_msg[0] = 1; 5017 5018 ssl->state++; 5019 5020 if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) 5021 { 5022 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); 5023 return( ret ); 5024 } 5025 5026 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) ); 5027 5028 return( 0 ); 5029 } 5030 5031 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ) 5032 { 5033 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 5034 5035 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) ); 5036 5037 if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) 5038 { 5039 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); 5040 return( ret ); 5041 } 5042 5043 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) 5044 { 5045 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); 5046 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, 5047 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); 5048 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); 5049 } 5050 5051 /* CCS records are only accepted if they have length 1 and content '1', 5052 * so we don't need to check this here. */ 5053 5054 /* 5055 * Switch to our negotiated transform and session parameters for inbound 5056 * data. 5057 */ 5058 MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) ); 5059 ssl->transform_in = ssl->transform_negotiate; 5060 ssl->session_in = ssl->session_negotiate; 5061 5062 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5063 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5064 { 5065 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) 5066 mbedtls_ssl_dtls_replay_reset( ssl ); 5067 #endif 5068 5069 /* Increment epoch */ 5070 if( ++ssl->in_epoch == 0 ) 5071 { 5072 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); 5073 /* This is highly unlikely to happen for legitimate reasons, so 5074 treat it as an attack and don't send an alert. */ 5075 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); 5076 } 5077 } 5078 else 5079 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 5080 memset( ssl->in_ctr, 0, 8 ); 5081 5082 mbedtls_ssl_update_in_pointers( ssl ); 5083 5084 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) 5085 if( mbedtls_ssl_hw_record_activate != NULL ) 5086 { 5087 if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 ) 5088 { 5089 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); 5090 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, 5091 MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); 5092 return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); 5093 } 5094 } 5095 #endif 5096 5097 ssl->state++; 5098 5099 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) ); 5100 5101 return( 0 ); 5102 } 5103 5104 /* Once ssl->out_hdr as the address of the beginning of the 5105 * next outgoing record is set, deduce the other pointers. 5106 * 5107 * Note: For TLS, we save the implicit record sequence number 5108 * (entering MAC computation) in the 8 bytes before ssl->out_hdr, 5109 * and the caller has to make sure there's space for this. 5110 */ 5111 5112 static size_t ssl_transform_get_explicit_iv_len( 5113 mbedtls_ssl_transform const *transform ) 5114 { 5115 if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) 5116 return( 0 ); 5117 5118 return( transform->ivlen - transform->fixed_ivlen ); 5119 } 5120 5121 void mbedtls_ssl_update_out_pointers( mbedtls_ssl_context *ssl, 5122 mbedtls_ssl_transform *transform ) 5123 { 5124 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5125 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5126 { 5127 ssl->out_ctr = ssl->out_hdr + 3; 5128 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 5129 ssl->out_cid = ssl->out_ctr + 8; 5130 ssl->out_len = ssl->out_cid; 5131 if( transform != NULL ) 5132 ssl->out_len += transform->out_cid_len; 5133 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 5134 ssl->out_len = ssl->out_ctr + 8; 5135 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 5136 ssl->out_iv = ssl->out_len + 2; 5137 } 5138 else 5139 #endif 5140 { 5141 ssl->out_ctr = ssl->out_hdr - 8; 5142 ssl->out_len = ssl->out_hdr + 3; 5143 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 5144 ssl->out_cid = ssl->out_len; 5145 #endif 5146 ssl->out_iv = ssl->out_hdr + 5; 5147 } 5148 5149 ssl->out_msg = ssl->out_iv; 5150 /* Adjust out_msg to make space for explicit IV, if used. */ 5151 if( transform != NULL ) 5152 ssl->out_msg += ssl_transform_get_explicit_iv_len( transform ); 5153 } 5154 5155 /* Once ssl->in_hdr as the address of the beginning of the 5156 * next incoming record is set, deduce the other pointers. 5157 * 5158 * Note: For TLS, we save the implicit record sequence number 5159 * (entering MAC computation) in the 8 bytes before ssl->in_hdr, 5160 * and the caller has to make sure there's space for this. 5161 */ 5162 5163 void mbedtls_ssl_update_in_pointers( mbedtls_ssl_context *ssl ) 5164 { 5165 /* This function sets the pointers to match the case 5166 * of unprotected TLS/DTLS records, with both ssl->in_iv 5167 * and ssl->in_msg pointing to the beginning of the record 5168 * content. 5169 * 5170 * When decrypting a protected record, ssl->in_msg 5171 * will be shifted to point to the beginning of the 5172 * record plaintext. 5173 */ 5174 5175 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5176 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5177 { 5178 /* This sets the header pointers to match records 5179 * without CID. When we receive a record containing 5180 * a CID, the fields are shifted accordingly in 5181 * ssl_parse_record_header(). */ 5182 ssl->in_ctr = ssl->in_hdr + 3; 5183 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 5184 ssl->in_cid = ssl->in_ctr + 8; 5185 ssl->in_len = ssl->in_cid; /* Default: no CID */ 5186 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 5187 ssl->in_len = ssl->in_ctr + 8; 5188 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 5189 ssl->in_iv = ssl->in_len + 2; 5190 } 5191 else 5192 #endif 5193 { 5194 ssl->in_ctr = ssl->in_hdr - 8; 5195 ssl->in_len = ssl->in_hdr + 3; 5196 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 5197 ssl->in_cid = ssl->in_len; 5198 #endif 5199 ssl->in_iv = ssl->in_hdr + 5; 5200 } 5201 5202 /* This will be adjusted at record decryption time. */ 5203 ssl->in_msg = ssl->in_iv; 5204 } 5205 5206 /* 5207 * Setup an SSL context 5208 */ 5209 5210 void mbedtls_ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl ) 5211 { 5212 /* Set the incoming and outgoing record pointers. */ 5213 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5214 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5215 { 5216 ssl->out_hdr = ssl->out_buf; 5217 ssl->in_hdr = ssl->in_buf; 5218 } 5219 else 5220 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 5221 { 5222 ssl->out_hdr = ssl->out_buf + 8; 5223 ssl->in_hdr = ssl->in_buf + 8; 5224 } 5225 5226 /* Derive other internal pointers. */ 5227 mbedtls_ssl_update_out_pointers( ssl, NULL /* no transform enabled */ ); 5228 mbedtls_ssl_update_in_pointers ( ssl ); 5229 } 5230 5231 /* 5232 * SSL get accessors 5233 */ 5234 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ) 5235 { 5236 return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); 5237 } 5238 5239 int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ) 5240 { 5241 /* 5242 * Case A: We're currently holding back 5243 * a message for further processing. 5244 */ 5245 5246 if( ssl->keep_current_message == 1 ) 5247 { 5248 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) ); 5249 return( 1 ); 5250 } 5251 5252 /* 5253 * Case B: Further records are pending in the current datagram. 5254 */ 5255 5256 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5257 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 5258 ssl->in_left > ssl->next_record_offset ) 5259 { 5260 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) ); 5261 return( 1 ); 5262 } 5263 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 5264 5265 /* 5266 * Case C: A handshake message is being processed. 5267 */ 5268 5269 if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen ) 5270 { 5271 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) ); 5272 return( 1 ); 5273 } 5274 5275 /* 5276 * Case D: An application data message is being processed 5277 */ 5278 if( ssl->in_offt != NULL ) 5279 { 5280 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) ); 5281 return( 1 ); 5282 } 5283 5284 /* 5285 * In all other cases, the rest of the message can be dropped. 5286 * As in ssl_get_next_record, this needs to be adapted if 5287 * we implement support for multiple alerts in single records. 5288 */ 5289 5290 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) ); 5291 return( 0 ); 5292 } 5293 5294 5295 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ) 5296 { 5297 size_t transform_expansion = 0; 5298 const mbedtls_ssl_transform *transform = ssl->transform_out; 5299 unsigned block_size; 5300 5301 size_t out_hdr_len = mbedtls_ssl_out_hdr_len( ssl ); 5302 5303 if( transform == NULL ) 5304 return( (int) out_hdr_len ); 5305 5306 #if defined(MBEDTLS_ZLIB_SUPPORT) 5307 if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL ) 5308 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); 5309 #endif 5310 5311 switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) ) 5312 { 5313 case MBEDTLS_MODE_GCM: 5314 case MBEDTLS_MODE_CCM: 5315 case MBEDTLS_MODE_CHACHAPOLY: 5316 case MBEDTLS_MODE_STREAM: 5317 transform_expansion = transform->minlen; 5318 break; 5319 5320 case MBEDTLS_MODE_CBC: 5321 5322 block_size = mbedtls_cipher_get_block_size( 5323 &transform->cipher_ctx_enc ); 5324 5325 /* Expansion due to the addition of the MAC. */ 5326 transform_expansion += transform->maclen; 5327 5328 /* Expansion due to the addition of CBC padding; 5329 * Theoretically up to 256 bytes, but we never use 5330 * more than the block size of the underlying cipher. */ 5331 transform_expansion += block_size; 5332 5333 /* For TLS 1.1 or higher, an explicit IV is added 5334 * after the record header. */ 5335 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) 5336 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) 5337 transform_expansion += block_size; 5338 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ 5339 5340 break; 5341 5342 default: 5343 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 5344 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 5345 } 5346 5347 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) 5348 if( transform->out_cid_len != 0 ) 5349 transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION; 5350 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ 5351 5352 return( (int)( out_hdr_len + transform_expansion ) ); 5353 } 5354 5355 #if defined(MBEDTLS_SSL_RENEGOTIATION) 5356 /* 5357 * Check record counters and renegotiate if they're above the limit. 5358 */ 5359 MBEDTLS_CHECK_RETURN_CRITICAL 5360 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl ) 5361 { 5362 size_t ep_len = mbedtls_ssl_ep_len( ssl ); 5363 int in_ctr_cmp; 5364 int out_ctr_cmp; 5365 5366 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER || 5367 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING || 5368 ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ) 5369 { 5370 return( 0 ); 5371 } 5372 5373 in_ctr_cmp = memcmp( ssl->in_ctr + ep_len, 5374 ssl->conf->renego_period + ep_len, 8 - ep_len ); 5375 out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len, 5376 ssl->conf->renego_period + ep_len, 8 - ep_len ); 5377 5378 if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 ) 5379 { 5380 return( 0 ); 5381 } 5382 5383 MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) ); 5384 return( mbedtls_ssl_renegotiate( ssl ) ); 5385 } 5386 #endif /* MBEDTLS_SSL_RENEGOTIATION */ 5387 5388 /* 5389 * Receive application data decrypted from the SSL layer 5390 */ 5391 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) 5392 { 5393 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 5394 size_t n; 5395 5396 if( ssl == NULL || ssl->conf == NULL ) 5397 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 5398 5399 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) ); 5400 5401 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5402 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5403 { 5404 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) 5405 return( ret ); 5406 5407 if( ssl->handshake != NULL && 5408 ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) 5409 { 5410 if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) 5411 return( ret ); 5412 } 5413 } 5414 #endif 5415 5416 /* 5417 * Check if renegotiation is necessary and/or handshake is 5418 * in process. If yes, perform/continue, and fall through 5419 * if an unexpected packet is received while the client 5420 * is waiting for the ServerHello. 5421 * 5422 * (There is no equivalent to the last condition on 5423 * the server-side as it is not treated as within 5424 * a handshake while waiting for the ClientHello 5425 * after a renegotiation request.) 5426 */ 5427 5428 #if defined(MBEDTLS_SSL_RENEGOTIATION) 5429 ret = ssl_check_ctr_renegotiate( ssl ); 5430 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && 5431 ret != 0 ) 5432 { 5433 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); 5434 return( ret ); 5435 } 5436 #endif 5437 5438 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) 5439 { 5440 ret = mbedtls_ssl_handshake( ssl ); 5441 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && 5442 ret != 0 ) 5443 { 5444 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); 5445 return( ret ); 5446 } 5447 } 5448 5449 /* Loop as long as no application data record is available */ 5450 while( ssl->in_offt == NULL ) 5451 { 5452 /* Start timer if not already running */ 5453 if( ssl->f_get_timer != NULL && 5454 ssl->f_get_timer( ssl->p_timer ) == -1 ) 5455 { 5456 mbedtls_ssl_set_timer( ssl, ssl->conf->read_timeout ); 5457 } 5458 5459 if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) 5460 { 5461 if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) 5462 return( 0 ); 5463 5464 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); 5465 return( ret ); 5466 } 5467 5468 if( ssl->in_msglen == 0 && 5469 ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA ) 5470 { 5471 /* 5472 * OpenSSL sends empty messages to randomize the IV 5473 */ 5474 if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) 5475 { 5476 if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) 5477 return( 0 ); 5478 5479 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); 5480 return( ret ); 5481 } 5482 } 5483 5484 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) 5485 { 5486 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); 5487 5488 /* 5489 * - For client-side, expect SERVER_HELLO_REQUEST. 5490 * - For server-side, expect CLIENT_HELLO. 5491 * - Fail (TLS) or silently drop record (DTLS) in other cases. 5492 */ 5493 5494 #if defined(MBEDTLS_SSL_CLI_C) 5495 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && 5496 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST || 5497 ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) ) 5498 { 5499 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) ); 5500 5501 /* With DTLS, drop the packet (probably from last handshake) */ 5502 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5503 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5504 { 5505 continue; 5506 } 5507 #endif 5508 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); 5509 } 5510 #endif /* MBEDTLS_SSL_CLI_C */ 5511 5512 #if defined(MBEDTLS_SSL_SRV_C) 5513 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && 5514 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) 5515 { 5516 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) ); 5517 5518 /* With DTLS, drop the packet (probably from last handshake) */ 5519 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5520 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5521 { 5522 continue; 5523 } 5524 #endif 5525 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); 5526 } 5527 #endif /* MBEDTLS_SSL_SRV_C */ 5528 5529 #if defined(MBEDTLS_SSL_RENEGOTIATION) 5530 /* Determine whether renegotiation attempt should be accepted */ 5531 if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED || 5532 ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && 5533 ssl->conf->allow_legacy_renegotiation == 5534 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) ) 5535 { 5536 /* 5537 * Accept renegotiation request 5538 */ 5539 5540 /* DTLS clients need to know renego is server-initiated */ 5541 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5542 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && 5543 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) 5544 { 5545 ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; 5546 } 5547 #endif 5548 ret = mbedtls_ssl_start_renegotiation( ssl ); 5549 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO && 5550 ret != 0 ) 5551 { 5552 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_start_renegotiation", 5553 ret ); 5554 return( ret ); 5555 } 5556 } 5557 else 5558 #endif /* MBEDTLS_SSL_RENEGOTIATION */ 5559 { 5560 /* 5561 * Refuse renegotiation 5562 */ 5563 5564 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) ); 5565 5566 #if defined(MBEDTLS_SSL_PROTO_SSL3) 5567 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) 5568 { 5569 /* SSLv3 does not have a "no_renegotiation" warning, so 5570 we send a fatal alert and abort the connection. */ 5571 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, 5572 MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); 5573 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); 5574 } 5575 else 5576 #endif /* MBEDTLS_SSL_PROTO_SSL3 */ 5577 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ 5578 defined(MBEDTLS_SSL_PROTO_TLS1_2) 5579 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) 5580 { 5581 if( ( ret = mbedtls_ssl_send_alert_message( ssl, 5582 MBEDTLS_SSL_ALERT_LEVEL_WARNING, 5583 MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 ) 5584 { 5585 return( ret ); 5586 } 5587 } 5588 else 5589 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || 5590 MBEDTLS_SSL_PROTO_TLS1_2 */ 5591 { 5592 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); 5593 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); 5594 } 5595 } 5596 5597 /* At this point, we don't know whether the renegotiation has been 5598 * completed or not. The cases to consider are the following: 5599 * 1) The renegotiation is complete. In this case, no new record 5600 * has been read yet. 5601 * 2) The renegotiation is incomplete because the client received 5602 * an application data record while awaiting the ServerHello. 5603 * 3) The renegotiation is incomplete because the client received 5604 * a non-handshake, non-application data message while awaiting 5605 * the ServerHello. 5606 * In each of these case, looping will be the proper action: 5607 * - For 1), the next iteration will read a new record and check 5608 * if it's application data. 5609 * - For 2), the loop condition isn't satisfied as application data 5610 * is present, hence continue is the same as break 5611 * - For 3), the loop condition is satisfied and read_record 5612 * will re-deliver the message that was held back by the client 5613 * when expecting the ServerHello. 5614 */ 5615 continue; 5616 } 5617 #if defined(MBEDTLS_SSL_RENEGOTIATION) 5618 else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) 5619 { 5620 if( ssl->conf->renego_max_records >= 0 ) 5621 { 5622 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records ) 5623 { 5624 MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, " 5625 "but not honored by client" ) ); 5626 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); 5627 } 5628 } 5629 } 5630 #endif /* MBEDTLS_SSL_RENEGOTIATION */ 5631 5632 /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */ 5633 if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) 5634 { 5635 MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) ); 5636 return( MBEDTLS_ERR_SSL_WANT_READ ); 5637 } 5638 5639 if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) 5640 { 5641 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) ); 5642 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); 5643 } 5644 5645 ssl->in_offt = ssl->in_msg; 5646 5647 /* We're going to return something now, cancel timer, 5648 * except if handshake (renegotiation) is in progress */ 5649 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) 5650 mbedtls_ssl_set_timer( ssl, 0 ); 5651 5652 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5653 /* If we requested renego but received AppData, resend HelloRequest. 5654 * Do it now, after setting in_offt, to avoid taking this branch 5655 * again if ssl_write_hello_request() returns WANT_WRITE */ 5656 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) 5657 if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && 5658 ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) 5659 { 5660 if( ( ret = mbedtls_ssl_resend_hello_request( ssl ) ) != 0 ) 5661 { 5662 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend_hello_request", 5663 ret ); 5664 return( ret ); 5665 } 5666 } 5667 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ 5668 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 5669 } 5670 5671 n = ( len < ssl->in_msglen ) 5672 ? len : ssl->in_msglen; 5673 5674 memcpy( buf, ssl->in_offt, n ); 5675 ssl->in_msglen -= n; 5676 5677 /* Zeroising the plaintext buffer to erase unused application data 5678 from the memory. */ 5679 mbedtls_platform_zeroize( ssl->in_offt, n ); 5680 5681 if( ssl->in_msglen == 0 ) 5682 { 5683 /* all bytes consumed */ 5684 ssl->in_offt = NULL; 5685 ssl->keep_current_message = 0; 5686 } 5687 else 5688 { 5689 /* more data available */ 5690 ssl->in_offt += n; 5691 } 5692 5693 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) ); 5694 5695 return( (int) n ); 5696 } 5697 5698 /* 5699 * Send application data to be encrypted by the SSL layer, taking care of max 5700 * fragment length and buffer size. 5701 * 5702 * According to RFC 5246 Section 6.2.1: 5703 * 5704 * Zero-length fragments of Application data MAY be sent as they are 5705 * potentially useful as a traffic analysis countermeasure. 5706 * 5707 * Therefore, it is possible that the input message length is 0 and the 5708 * corresponding return code is 0 on success. 5709 */ 5710 MBEDTLS_CHECK_RETURN_CRITICAL 5711 static int ssl_write_real( mbedtls_ssl_context *ssl, 5712 const unsigned char *buf, size_t len ) 5713 { 5714 int ret = mbedtls_ssl_get_max_out_record_payload( ssl ); 5715 const size_t max_len = (size_t) ret; 5716 5717 if( ret < 0 ) 5718 { 5719 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret ); 5720 return( ret ); 5721 } 5722 5723 if( len > max_len ) 5724 { 5725 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5726 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5727 { 5728 MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) " 5729 "maximum fragment length: %" MBEDTLS_PRINTF_SIZET 5730 " > %" MBEDTLS_PRINTF_SIZET, 5731 len, max_len ) ); 5732 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 5733 } 5734 else 5735 #endif 5736 len = max_len; 5737 } 5738 5739 if( ssl->out_left != 0 ) 5740 { 5741 /* 5742 * The user has previously tried to send the data and 5743 * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially 5744 * written. In this case, we expect the high-level write function 5745 * (e.g. mbedtls_ssl_write()) to be called with the same parameters 5746 */ 5747 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) 5748 { 5749 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); 5750 return( ret ); 5751 } 5752 } 5753 else 5754 { 5755 /* 5756 * The user is trying to send a message the first time, so we need to 5757 * copy the data into the internal buffers and setup the data structure 5758 * to keep track of partial writes 5759 */ 5760 ssl->out_msglen = len; 5761 ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA; 5762 memcpy( ssl->out_msg, buf, len ); 5763 5764 if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 ) 5765 { 5766 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); 5767 return( ret ); 5768 } 5769 } 5770 5771 return( (int) len ); 5772 } 5773 5774 /* 5775 * Write application data, doing 1/n-1 splitting if necessary. 5776 * 5777 * With non-blocking I/O, ssl_write_real() may return WANT_WRITE, 5778 * then the caller will call us again with the same arguments, so 5779 * remember whether we already did the split or not. 5780 */ 5781 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) 5782 MBEDTLS_CHECK_RETURN_CRITICAL 5783 static int ssl_write_split( mbedtls_ssl_context *ssl, 5784 const unsigned char *buf, size_t len ) 5785 { 5786 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 5787 5788 if( ssl->conf->cbc_record_splitting == 5789 MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED || 5790 len <= 1 || 5791 ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 || 5792 mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ) 5793 != MBEDTLS_MODE_CBC ) 5794 { 5795 return( ssl_write_real( ssl, buf, len ) ); 5796 } 5797 5798 if( ssl->split_done == 0 ) 5799 { 5800 if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 ) 5801 return( ret ); 5802 ssl->split_done = 1; 5803 } 5804 5805 if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 ) 5806 return( ret ); 5807 ssl->split_done = 0; 5808 5809 return( ret + 1 ); 5810 } 5811 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ 5812 5813 /* 5814 * Write application data (public-facing wrapper) 5815 */ 5816 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) 5817 { 5818 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 5819 5820 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) ); 5821 5822 if( ssl == NULL || ssl->conf == NULL ) 5823 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 5824 5825 #if defined(MBEDTLS_SSL_RENEGOTIATION) 5826 if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) 5827 { 5828 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); 5829 return( ret ); 5830 } 5831 #endif 5832 5833 if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) 5834 { 5835 if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) 5836 { 5837 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); 5838 return( ret ); 5839 } 5840 } 5841 5842 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) 5843 ret = ssl_write_split( ssl, buf, len ); 5844 #else 5845 ret = ssl_write_real( ssl, buf, len ); 5846 #endif 5847 5848 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) ); 5849 5850 return( ret ); 5851 } 5852 5853 /* 5854 * Notify the peer that the connection is being closed 5855 */ 5856 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ) 5857 { 5858 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; 5859 5860 if( ssl == NULL || ssl->conf == NULL ) 5861 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); 5862 5863 MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) ); 5864 5865 if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) 5866 { 5867 if( ( ret = mbedtls_ssl_send_alert_message( ssl, 5868 MBEDTLS_SSL_ALERT_LEVEL_WARNING, 5869 MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 ) 5870 { 5871 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret ); 5872 return( ret ); 5873 } 5874 } 5875 5876 MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) ); 5877 5878 return( 0 ); 5879 } 5880 5881 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ) 5882 { 5883 if( transform == NULL ) 5884 return; 5885 5886 #if defined(MBEDTLS_ZLIB_SUPPORT) 5887 deflateEnd( &transform->ctx_deflate ); 5888 inflateEnd( &transform->ctx_inflate ); 5889 #endif 5890 5891 mbedtls_cipher_free( &transform->cipher_ctx_enc ); 5892 mbedtls_cipher_free( &transform->cipher_ctx_dec ); 5893 5894 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) 5895 mbedtls_md_free( &transform->md_ctx_enc ); 5896 mbedtls_md_free( &transform->md_ctx_dec ); 5897 #endif 5898 5899 mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); 5900 } 5901 5902 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5903 5904 void mbedtls_ssl_buffering_free( mbedtls_ssl_context *ssl ) 5905 { 5906 unsigned offset; 5907 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 5908 5909 if( hs == NULL ) 5910 return; 5911 5912 ssl_free_buffered_record( ssl ); 5913 5914 for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ ) 5915 ssl_buffering_free_slot( ssl, offset ); 5916 } 5917 5918 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl, 5919 uint8_t slot ) 5920 { 5921 mbedtls_ssl_handshake_params * const hs = ssl->handshake; 5922 mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot]; 5923 5924 if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS ) 5925 return; 5926 5927 if( hs_buf->is_valid == 1 ) 5928 { 5929 hs->buffering.total_bytes_buffered -= hs_buf->data_len; 5930 mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len ); 5931 mbedtls_free( hs_buf->data ); 5932 memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) ); 5933 } 5934 } 5935 5936 #endif /* MBEDTLS_SSL_PROTO_DTLS */ 5937 5938 /* 5939 * Convert version numbers to/from wire format 5940 * and, for DTLS, to/from TLS equivalent. 5941 * 5942 * For TLS this is the identity. 5943 * For DTLS, use 1's complement (v -> 255 - v, and then map as follows: 5944 * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1) 5945 * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2) 5946 */ 5947 void mbedtls_ssl_write_version( int major, int minor, int transport, 5948 unsigned char ver[2] ) 5949 { 5950 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5951 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5952 { 5953 if( minor == MBEDTLS_SSL_MINOR_VERSION_2 ) 5954 --minor; /* DTLS 1.0 stored as TLS 1.1 internally */ 5955 5956 ver[0] = (unsigned char)( 255 - ( major - 2 ) ); 5957 ver[1] = (unsigned char)( 255 - ( minor - 1 ) ); 5958 } 5959 else 5960 #else 5961 ((void) transport); 5962 #endif 5963 { 5964 ver[0] = (unsigned char) major; 5965 ver[1] = (unsigned char) minor; 5966 } 5967 } 5968 5969 void mbedtls_ssl_read_version( int *major, int *minor, int transport, 5970 const unsigned char ver[2] ) 5971 { 5972 #if defined(MBEDTLS_SSL_PROTO_DTLS) 5973 if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) 5974 { 5975 *major = 255 - ver[0] + 2; 5976 *minor = 255 - ver[1] + 1; 5977 5978 if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 ) 5979 ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */ 5980 } 5981 else 5982 #else 5983 ((void) transport); 5984 #endif 5985 { 5986 *major = ver[0]; 5987 *minor = ver[1]; 5988 } 5989 } 5990 5991 #endif /* MBEDTLS_SSL_TLS_C */ 5992