1 /* 2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. 3 * 4 * Licensed under the OpenSSL license (the "License"). You may not use 5 * this file except in compliance with the License. You can obtain a copy 6 * in the file LICENSE in the source distribution or at 7 * https://www.openssl.org/source/license.html 8 */ 9 10 #include <stdio.h> 11 #include <limits.h> 12 #include <errno.h> 13 #include "../ssl_local.h" 14 #include <openssl/evp.h> 15 #include <openssl/buffer.h> 16 #include <openssl/rand.h> 17 #include "record_local.h" 18 #include "../packet_local.h" 19 20 #if defined(OPENSSL_SMALL_FOOTPRINT) || \ 21 !( defined(AESNI_ASM) && ( \ 22 defined(__x86_64) || defined(__x86_64__) || \ 23 defined(_M_AMD64) || defined(_M_X64) ) \ 24 ) 25 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 26 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0 27 #endif 28 29 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s) 30 { 31 rl->s = s; 32 RECORD_LAYER_set_first_record(&s->rlayer); 33 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES); 34 } 35 36 void RECORD_LAYER_clear(RECORD_LAYER *rl) 37 { 38 rl->rstate = SSL_ST_READ_HEADER; 39 40 /* 41 * Do I need to clear read_ahead? As far as I can tell read_ahead did not 42 * previously get reset by SSL_clear...so I'll keep it that way..but is 43 * that right? 44 */ 45 46 rl->packet = NULL; 47 rl->packet_length = 0; 48 rl->wnum = 0; 49 memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment)); 50 rl->handshake_fragment_len = 0; 51 rl->wpend_tot = 0; 52 rl->wpend_type = 0; 53 rl->wpend_ret = 0; 54 rl->wpend_buf = NULL; 55 56 SSL3_BUFFER_clear(&rl->rbuf); 57 ssl3_release_write_buffer(rl->s); 58 rl->numrpipes = 0; 59 SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES); 60 61 RECORD_LAYER_reset_read_sequence(rl); 62 RECORD_LAYER_reset_write_sequence(rl); 63 64 if (rl->d) 65 DTLS_RECORD_LAYER_clear(rl); 66 } 67 68 void RECORD_LAYER_release(RECORD_LAYER *rl) 69 { 70 if (SSL3_BUFFER_is_initialised(&rl->rbuf)) 71 ssl3_release_read_buffer(rl->s); 72 if (rl->numwpipes > 0) 73 ssl3_release_write_buffer(rl->s); 74 SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES); 75 } 76 77 /* Checks if we have unprocessed read ahead data pending */ 78 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl) 79 { 80 return SSL3_BUFFER_get_left(&rl->rbuf) != 0; 81 } 82 83 /* Checks if we have decrypted unread record data pending */ 84 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl) 85 { 86 size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl); 87 const SSL3_RECORD *rr = rl->rrec; 88 89 while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec])) 90 curr_rec++; 91 92 return curr_rec < num_recs; 93 } 94 95 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl) 96 { 97 return (rl->numwpipes > 0) 98 && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0; 99 } 100 101 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl) 102 { 103 memset(rl->read_sequence, 0, sizeof(rl->read_sequence)); 104 } 105 106 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl) 107 { 108 memset(rl->write_sequence, 0, sizeof(rl->write_sequence)); 109 } 110 111 size_t ssl3_pending(const SSL *s) 112 { 113 size_t i, num = 0; 114 115 if (s->rlayer.rstate == SSL_ST_READ_BODY) 116 return 0; 117 118 for (i = 0; i < RECORD_LAYER_get_numrpipes(&s->rlayer); i++) { 119 if (SSL3_RECORD_get_type(&s->rlayer.rrec[i]) 120 != SSL3_RT_APPLICATION_DATA) 121 return 0; 122 num += SSL3_RECORD_get_length(&s->rlayer.rrec[i]); 123 } 124 125 return num; 126 } 127 128 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len) 129 { 130 ctx->default_read_buf_len = len; 131 } 132 133 void SSL_set_default_read_buffer_len(SSL *s, size_t len) 134 { 135 SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&s->rlayer), len); 136 } 137 138 const char *SSL_rstate_string_long(const SSL *s) 139 { 140 switch (s->rlayer.rstate) { 141 case SSL_ST_READ_HEADER: 142 return "read header"; 143 case SSL_ST_READ_BODY: 144 return "read body"; 145 case SSL_ST_READ_DONE: 146 return "read done"; 147 default: 148 return "unknown"; 149 } 150 } 151 152 const char *SSL_rstate_string(const SSL *s) 153 { 154 switch (s->rlayer.rstate) { 155 case SSL_ST_READ_HEADER: 156 return "RH"; 157 case SSL_ST_READ_BODY: 158 return "RB"; 159 case SSL_ST_READ_DONE: 160 return "RD"; 161 default: 162 return "unknown"; 163 } 164 } 165 166 /* 167 * Return values are as per SSL_read() 168 */ 169 int ssl3_read_n(SSL *s, size_t n, size_t max, int extend, int clearold, 170 size_t *readbytes) 171 { 172 /* 173 * If extend == 0, obtain new n-byte packet; if extend == 1, increase 174 * packet by another n bytes. The packet will be in the sub-array of 175 * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If 176 * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus 177 * s->packet_length bytes if extend == 1].) 178 * if clearold == 1, move the packet to the start of the buffer; if 179 * clearold == 0 then leave any old packets where they were 180 */ 181 size_t len, left, align = 0; 182 unsigned char *pkt; 183 SSL3_BUFFER *rb; 184 185 if (n == 0) 186 return 0; 187 188 rb = &s->rlayer.rbuf; 189 if (rb->buf == NULL) 190 if (!ssl3_setup_read_buffer(s)) { 191 /* SSLfatal() already called */ 192 return -1; 193 } 194 195 left = rb->left; 196 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 197 align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH; 198 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); 199 #endif 200 201 if (!extend) { 202 /* start with empty packet ... */ 203 if (left == 0) 204 rb->offset = align; 205 else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) { 206 /* 207 * check if next packet length is large enough to justify payload 208 * alignment... 209 */ 210 pkt = rb->buf + rb->offset; 211 if (pkt[0] == SSL3_RT_APPLICATION_DATA 212 && (pkt[3] << 8 | pkt[4]) >= 128) { 213 /* 214 * Note that even if packet is corrupted and its length field 215 * is insane, we can only be led to wrong decision about 216 * whether memmove will occur or not. Header values has no 217 * effect on memmove arguments and therefore no buffer 218 * overrun can be triggered. 219 */ 220 memmove(rb->buf + align, pkt, left); 221 rb->offset = align; 222 } 223 } 224 s->rlayer.packet = rb->buf + rb->offset; 225 s->rlayer.packet_length = 0; 226 /* ... now we can act as if 'extend' was set */ 227 } 228 229 len = s->rlayer.packet_length; 230 pkt = rb->buf + align; 231 /* 232 * Move any available bytes to front of buffer: 'len' bytes already 233 * pointed to by 'packet', 'left' extra ones at the end 234 */ 235 if (s->rlayer.packet != pkt && clearold == 1) { 236 memmove(pkt, s->rlayer.packet, len + left); 237 s->rlayer.packet = pkt; 238 rb->offset = len + align; 239 } 240 241 /* 242 * For DTLS/UDP reads should not span multiple packets because the read 243 * operation returns the whole packet at once (as long as it fits into 244 * the buffer). 245 */ 246 if (SSL_IS_DTLS(s)) { 247 if (left == 0 && extend) 248 return 0; 249 if (left > 0 && n > left) 250 n = left; 251 } 252 253 /* if there is enough in the buffer from a previous read, take some */ 254 if (left >= n) { 255 s->rlayer.packet_length += n; 256 rb->left = left - n; 257 rb->offset += n; 258 *readbytes = n; 259 return 1; 260 } 261 262 /* else we need to read more data */ 263 264 if (n > rb->len - rb->offset) { 265 /* does not happen */ 266 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_READ_N, 267 ERR_R_INTERNAL_ERROR); 268 return -1; 269 } 270 271 /* We always act like read_ahead is set for DTLS */ 272 if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s)) 273 /* ignore max parameter */ 274 max = n; 275 else { 276 if (max < n) 277 max = n; 278 if (max > rb->len - rb->offset) 279 max = rb->len - rb->offset; 280 } 281 282 while (left < n) { 283 size_t bioread = 0; 284 int ret; 285 286 /* 287 * Now we have len+left bytes at the front of s->s3->rbuf.buf and 288 * need to read in more until we have len+n (up to len+max if 289 * possible) 290 */ 291 292 clear_sys_error(); 293 if (s->rbio != NULL) { 294 s->rwstate = SSL_READING; 295 /* TODO(size_t): Convert this function */ 296 ret = BIO_read(s->rbio, pkt + len + left, max - left); 297 if (ret >= 0) 298 bioread = ret; 299 if (ret <= 0 300 && !BIO_should_retry(s->rbio) 301 && BIO_eof(s->rbio)) { 302 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_READ_N, 303 SSL_R_UNEXPECTED_EOF_WHILE_READING); 304 } 305 } else { 306 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_READ_N, 307 SSL_R_READ_BIO_NOT_SET); 308 ret = -1; 309 } 310 311 if (ret <= 0) { 312 rb->left = left; 313 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) 314 if (len + left == 0) 315 ssl3_release_read_buffer(s); 316 return ret; 317 } 318 left += bioread; 319 /* 320 * reads should *never* span multiple packets for DTLS because the 321 * underlying transport protocol is message oriented as opposed to 322 * byte oriented as in the TLS case. 323 */ 324 if (SSL_IS_DTLS(s)) { 325 if (n > left) 326 n = left; /* makes the while condition false */ 327 } 328 } 329 330 /* done reading, now the book-keeping */ 331 rb->offset += n; 332 rb->left = left - n; 333 s->rlayer.packet_length += n; 334 s->rwstate = SSL_NOTHING; 335 *readbytes = n; 336 return 1; 337 } 338 339 /* 340 * Call this to write data in records of type 'type' It will return <= 0 if 341 * not all data has been sent or non-blocking IO. 342 */ 343 int ssl3_write_bytes(SSL *s, int type, const void *buf_, size_t len, 344 size_t *written) 345 { 346 const unsigned char *buf = buf_; 347 size_t tot; 348 size_t n, max_send_fragment, split_send_fragment, maxpipes; 349 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 350 size_t nw; 351 #endif 352 SSL3_BUFFER *wb = &s->rlayer.wbuf[0]; 353 int i; 354 size_t tmpwrit; 355 356 s->rwstate = SSL_NOTHING; 357 tot = s->rlayer.wnum; 358 /* 359 * ensure that if we end up with a smaller value of data to write out 360 * than the original len from a write which didn't complete for 361 * non-blocking I/O and also somehow ended up avoiding the check for 362 * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be 363 * possible to end up with (len-tot) as a large number that will then 364 * promptly send beyond the end of the users buffer ... so we trap and 365 * report the error in a way the user will notice 366 */ 367 if ((len < s->rlayer.wnum) 368 || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) { 369 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_WRITE_BYTES, 370 SSL_R_BAD_LENGTH); 371 return -1; 372 } 373 374 if (s->early_data_state == SSL_EARLY_DATA_WRITING 375 && !early_data_count_ok(s, len, 0, 1)) { 376 /* SSLfatal() already called */ 377 return -1; 378 } 379 380 s->rlayer.wnum = 0; 381 382 /* 383 * If we are supposed to be sending a KeyUpdate then go into init unless we 384 * have writes pending - in which case we should finish doing that first. 385 */ 386 if (wb->left == 0 && s->key_update != SSL_KEY_UPDATE_NONE) 387 ossl_statem_set_in_init(s, 1); 388 389 /* 390 * When writing early data on the server side we could be "in_init" in 391 * between receiving the EoED and the CF - but we don't want to handle those 392 * messages yet. 393 */ 394 if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s) 395 && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) { 396 i = s->handshake_func(s); 397 /* SSLfatal() already called */ 398 if (i < 0) 399 return i; 400 if (i == 0) { 401 return -1; 402 } 403 } 404 405 /* 406 * first check if there is a SSL3_BUFFER still being written out. This 407 * will happen with non blocking IO 408 */ 409 if (wb->left != 0) { 410 /* SSLfatal() already called if appropriate */ 411 i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot, 412 &tmpwrit); 413 if (i <= 0) { 414 /* XXX should we ssl3_release_write_buffer if i<0? */ 415 s->rlayer.wnum = tot; 416 return i; 417 } 418 tot += tmpwrit; /* this might be last fragment */ 419 } 420 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 421 /* 422 * Depending on platform multi-block can deliver several *times* 423 * better performance. Downside is that it has to allocate 424 * jumbo buffer to accommodate up to 8 records, but the 425 * compromise is considered worthy. 426 */ 427 if (type == SSL3_RT_APPLICATION_DATA && 428 len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s)) && 429 s->compress == NULL && s->msg_callback == NULL && 430 !SSL_WRITE_ETM(s) && SSL_USE_EXPLICIT_IV(s) && 431 EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) & 432 EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { 433 unsigned char aad[13]; 434 EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; 435 size_t packlen; 436 int packleni; 437 438 /* minimize address aliasing conflicts */ 439 if ((max_send_fragment & 0xfff) == 0) 440 max_send_fragment -= 512; 441 442 if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */ 443 ssl3_release_write_buffer(s); 444 445 packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, 446 EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE, 447 (int)max_send_fragment, NULL); 448 449 if (len >= 8 * max_send_fragment) 450 packlen *= 8; 451 else 452 packlen *= 4; 453 454 if (!ssl3_setup_write_buffer(s, 1, packlen)) { 455 /* SSLfatal() already called */ 456 return -1; 457 } 458 } else if (tot == len) { /* done? */ 459 /* free jumbo buffer */ 460 ssl3_release_write_buffer(s); 461 *written = tot; 462 return 1; 463 } 464 465 n = (len - tot); 466 for (;;) { 467 if (n < 4 * max_send_fragment) { 468 /* free jumbo buffer */ 469 ssl3_release_write_buffer(s); 470 break; 471 } 472 473 if (s->s3->alert_dispatch) { 474 i = s->method->ssl_dispatch_alert(s); 475 if (i <= 0) { 476 /* SSLfatal() already called if appropriate */ 477 s->rlayer.wnum = tot; 478 return i; 479 } 480 } 481 482 if (n >= 8 * max_send_fragment) 483 nw = max_send_fragment * (mb_param.interleave = 8); 484 else 485 nw = max_send_fragment * (mb_param.interleave = 4); 486 487 memcpy(aad, s->rlayer.write_sequence, 8); 488 aad[8] = type; 489 aad[9] = (unsigned char)(s->version >> 8); 490 aad[10] = (unsigned char)(s->version); 491 aad[11] = 0; 492 aad[12] = 0; 493 mb_param.out = NULL; 494 mb_param.inp = aad; 495 mb_param.len = nw; 496 497 packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, 498 EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, 499 sizeof(mb_param), &mb_param); 500 packlen = (size_t)packleni; 501 if (packleni <= 0 || packlen > wb->len) { /* never happens */ 502 /* free jumbo buffer */ 503 ssl3_release_write_buffer(s); 504 break; 505 } 506 507 mb_param.out = wb->buf; 508 mb_param.inp = &buf[tot]; 509 mb_param.len = nw; 510 511 if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, 512 EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, 513 sizeof(mb_param), &mb_param) <= 0) 514 return -1; 515 516 s->rlayer.write_sequence[7] += mb_param.interleave; 517 if (s->rlayer.write_sequence[7] < mb_param.interleave) { 518 int j = 6; 519 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ; 520 } 521 522 wb->offset = 0; 523 wb->left = packlen; 524 525 s->rlayer.wpend_tot = nw; 526 s->rlayer.wpend_buf = &buf[tot]; 527 s->rlayer.wpend_type = type; 528 s->rlayer.wpend_ret = nw; 529 530 i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit); 531 if (i <= 0) { 532 /* SSLfatal() already called if appropriate */ 533 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) { 534 /* free jumbo buffer */ 535 ssl3_release_write_buffer(s); 536 } 537 s->rlayer.wnum = tot; 538 return i; 539 } 540 if (tmpwrit == n) { 541 /* free jumbo buffer */ 542 ssl3_release_write_buffer(s); 543 *written = tot + tmpwrit; 544 return 1; 545 } 546 n -= tmpwrit; 547 tot += tmpwrit; 548 } 549 } else 550 #endif /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */ 551 if (tot == len) { /* done? */ 552 if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) 553 ssl3_release_write_buffer(s); 554 555 *written = tot; 556 return 1; 557 } 558 559 n = (len - tot); 560 561 max_send_fragment = ssl_get_max_send_fragment(s); 562 split_send_fragment = ssl_get_split_send_fragment(s); 563 /* 564 * If max_pipelines is 0 then this means "undefined" and we default to 565 * 1 pipeline. Similarly if the cipher does not support pipelined 566 * processing then we also only use 1 pipeline, or if we're not using 567 * explicit IVs 568 */ 569 maxpipes = s->max_pipelines; 570 if (maxpipes > SSL_MAX_PIPELINES) { 571 /* 572 * We should have prevented this when we set max_pipelines so we 573 * shouldn't get here 574 */ 575 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_WRITE_BYTES, 576 ERR_R_INTERNAL_ERROR); 577 return -1; 578 } 579 if (maxpipes == 0 580 || s->enc_write_ctx == NULL 581 || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) 582 & EVP_CIPH_FLAG_PIPELINE) 583 || !SSL_USE_EXPLICIT_IV(s)) 584 maxpipes = 1; 585 if (max_send_fragment == 0 || split_send_fragment == 0 586 || split_send_fragment > max_send_fragment) { 587 /* 588 * We should have prevented this when we set/get the split and max send 589 * fragments so we shouldn't get here 590 */ 591 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_WRITE_BYTES, 592 ERR_R_INTERNAL_ERROR); 593 return -1; 594 } 595 596 for (;;) { 597 size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain; 598 size_t numpipes, j; 599 600 if (n == 0) 601 numpipes = 1; 602 else 603 numpipes = ((n - 1) / split_send_fragment) + 1; 604 if (numpipes > maxpipes) 605 numpipes = maxpipes; 606 607 if (n / numpipes >= max_send_fragment) { 608 /* 609 * We have enough data to completely fill all available 610 * pipelines 611 */ 612 for (j = 0; j < numpipes; j++) { 613 pipelens[j] = max_send_fragment; 614 } 615 } else { 616 /* We can partially fill all available pipelines */ 617 tmppipelen = n / numpipes; 618 remain = n % numpipes; 619 for (j = 0; j < numpipes; j++) { 620 pipelens[j] = tmppipelen; 621 if (j < remain) 622 pipelens[j]++; 623 } 624 } 625 626 i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0, 627 &tmpwrit); 628 if (i <= 0) { 629 /* SSLfatal() already called if appropriate */ 630 /* XXX should we ssl3_release_write_buffer if i<0? */ 631 s->rlayer.wnum = tot; 632 return i; 633 } 634 635 if (tmpwrit == n || 636 (type == SSL3_RT_APPLICATION_DATA && 637 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) { 638 /* 639 * next chunk of data should get another prepended empty fragment 640 * in ciphersuites with known-IV weakness: 641 */ 642 s->s3->empty_fragment_done = 0; 643 644 if (tmpwrit == n 645 && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0 646 && !SSL_IS_DTLS(s)) 647 ssl3_release_write_buffer(s); 648 649 *written = tot + tmpwrit; 650 return 1; 651 } 652 653 n -= tmpwrit; 654 tot += tmpwrit; 655 } 656 } 657 658 int do_ssl3_write(SSL *s, int type, const unsigned char *buf, 659 size_t *pipelens, size_t numpipes, 660 int create_empty_fragment, size_t *written) 661 { 662 WPACKET pkt[SSL_MAX_PIPELINES]; 663 SSL3_RECORD wr[SSL_MAX_PIPELINES]; 664 WPACKET *thispkt; 665 SSL3_RECORD *thiswr; 666 unsigned char *recordstart; 667 int i, mac_size, clear = 0; 668 size_t prefix_len = 0; 669 int eivlen = 0; 670 size_t align = 0; 671 SSL3_BUFFER *wb; 672 SSL_SESSION *sess; 673 size_t totlen = 0, len, wpinited = 0; 674 size_t j; 675 676 for (j = 0; j < numpipes; j++) 677 totlen += pipelens[j]; 678 /* 679 * first check if there is a SSL3_BUFFER still being written out. This 680 * will happen with non blocking IO 681 */ 682 if (RECORD_LAYER_write_pending(&s->rlayer)) { 683 /* Calls SSLfatal() as required */ 684 return ssl3_write_pending(s, type, buf, totlen, written); 685 } 686 687 /* If we have an alert to send, lets send it */ 688 if (s->s3->alert_dispatch) { 689 i = s->method->ssl_dispatch_alert(s); 690 if (i <= 0) { 691 /* SSLfatal() already called if appropriate */ 692 return i; 693 } 694 /* if it went, fall through and send more stuff */ 695 } 696 697 if (s->rlayer.numwpipes < numpipes) { 698 if (!ssl3_setup_write_buffer(s, numpipes, 0)) { 699 /* SSLfatal() already called */ 700 return -1; 701 } 702 } 703 704 if (totlen == 0 && !create_empty_fragment) 705 return 0; 706 707 sess = s->session; 708 709 if ((sess == NULL) || 710 (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL)) { 711 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */ 712 mac_size = 0; 713 } else { 714 /* TODO(siz_t): Convert me */ 715 mac_size = EVP_MD_CTX_size(s->write_hash); 716 if (mac_size < 0) { 717 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 718 ERR_R_INTERNAL_ERROR); 719 goto err; 720 } 721 } 722 723 /* 724 * 'create_empty_fragment' is true only when this function calls itself 725 */ 726 if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) { 727 /* 728 * countermeasure against known-IV weakness in CBC ciphersuites (see 729 * http://www.openssl.org/~bodo/tls-cbc.txt) 730 */ 731 732 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) { 733 /* 734 * recursive function call with 'create_empty_fragment' set; this 735 * prepares and buffers the data for an empty fragment (these 736 * 'prefix_len' bytes are sent out later together with the actual 737 * payload) 738 */ 739 size_t tmppipelen = 0; 740 int ret; 741 742 ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len); 743 if (ret <= 0) { 744 /* SSLfatal() already called if appropriate */ 745 goto err; 746 } 747 748 if (prefix_len > 749 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) { 750 /* insufficient space */ 751 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 752 ERR_R_INTERNAL_ERROR); 753 goto err; 754 } 755 } 756 757 s->s3->empty_fragment_done = 1; 758 } 759 760 if (create_empty_fragment) { 761 wb = &s->rlayer.wbuf[0]; 762 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 763 /* 764 * extra fragment would be couple of cipher blocks, which would be 765 * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real 766 * payload, then we can just pretend we simply have two headers. 767 */ 768 align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH; 769 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); 770 #endif 771 SSL3_BUFFER_set_offset(wb, align); 772 if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb), 773 SSL3_BUFFER_get_len(wb), 0) 774 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) { 775 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 776 ERR_R_INTERNAL_ERROR); 777 goto err; 778 } 779 wpinited = 1; 780 } else if (prefix_len) { 781 wb = &s->rlayer.wbuf[0]; 782 if (!WPACKET_init_static_len(&pkt[0], 783 SSL3_BUFFER_get_buf(wb), 784 SSL3_BUFFER_get_len(wb), 0) 785 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb) 786 + prefix_len, NULL)) { 787 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 788 ERR_R_INTERNAL_ERROR); 789 goto err; 790 } 791 wpinited = 1; 792 } else { 793 for (j = 0; j < numpipes; j++) { 794 thispkt = &pkt[j]; 795 796 wb = &s->rlayer.wbuf[j]; 797 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0 798 align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH; 799 align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); 800 #endif 801 SSL3_BUFFER_set_offset(wb, align); 802 if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb), 803 SSL3_BUFFER_get_len(wb), 0) 804 || !WPACKET_allocate_bytes(thispkt, align, NULL)) { 805 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 806 ERR_R_INTERNAL_ERROR); 807 goto err; 808 } 809 wpinited++; 810 } 811 } 812 813 /* Explicit IV length, block ciphers appropriate version flag */ 814 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s) && !SSL_TREAT_AS_TLS13(s)) { 815 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx); 816 if (mode == EVP_CIPH_CBC_MODE) { 817 /* TODO(size_t): Convert me */ 818 eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx); 819 if (eivlen <= 1) 820 eivlen = 0; 821 } else if (mode == EVP_CIPH_GCM_MODE) { 822 /* Need explicit part of IV for GCM mode */ 823 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN; 824 } else if (mode == EVP_CIPH_CCM_MODE) { 825 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN; 826 } 827 } 828 829 totlen = 0; 830 /* Clear our SSL3_RECORD structures */ 831 memset(wr, 0, sizeof(wr)); 832 for (j = 0; j < numpipes; j++) { 833 unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION 834 : s->version; 835 unsigned char *compressdata = NULL; 836 size_t maxcomplen; 837 unsigned int rectype; 838 839 thispkt = &pkt[j]; 840 thiswr = &wr[j]; 841 842 /* 843 * In TLSv1.3, once encrypting, we always use application data for the 844 * record type 845 */ 846 if (SSL_TREAT_AS_TLS13(s) 847 && s->enc_write_ctx != NULL 848 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS 849 || type != SSL3_RT_ALERT)) 850 rectype = SSL3_RT_APPLICATION_DATA; 851 else 852 rectype = type; 853 SSL3_RECORD_set_type(thiswr, rectype); 854 855 /* 856 * Some servers hang if initial client hello is larger than 256 bytes 857 * and record version number > TLS 1.0 858 */ 859 if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO 860 && !s->renegotiate 861 && TLS1_get_version(s) > TLS1_VERSION 862 && s->hello_retry_request == SSL_HRR_NONE) 863 version = TLS1_VERSION; 864 SSL3_RECORD_set_rec_version(thiswr, version); 865 866 maxcomplen = pipelens[j]; 867 if (s->compress != NULL) 868 maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD; 869 870 /* write the header */ 871 if (!WPACKET_put_bytes_u8(thispkt, rectype) 872 || !WPACKET_put_bytes_u16(thispkt, version) 873 || !WPACKET_start_sub_packet_u16(thispkt) 874 || (eivlen > 0 875 && !WPACKET_allocate_bytes(thispkt, eivlen, NULL)) 876 || (maxcomplen > 0 877 && !WPACKET_reserve_bytes(thispkt, maxcomplen, 878 &compressdata))) { 879 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 880 ERR_R_INTERNAL_ERROR); 881 goto err; 882 } 883 884 /* lets setup the record stuff. */ 885 SSL3_RECORD_set_data(thiswr, compressdata); 886 SSL3_RECORD_set_length(thiswr, pipelens[j]); 887 SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]); 888 totlen += pipelens[j]; 889 890 /* 891 * we now 'read' from thiswr->input, thiswr->length bytes into 892 * thiswr->data 893 */ 894 895 /* first we compress */ 896 if (s->compress != NULL) { 897 if (!ssl3_do_compress(s, thiswr) 898 || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) { 899 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 900 SSL_R_COMPRESSION_FAILURE); 901 goto err; 902 } 903 } else { 904 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) { 905 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 906 ERR_R_INTERNAL_ERROR); 907 goto err; 908 } 909 SSL3_RECORD_reset_input(&wr[j]); 910 } 911 912 if (SSL_TREAT_AS_TLS13(s) 913 && s->enc_write_ctx != NULL 914 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS 915 || type != SSL3_RT_ALERT)) { 916 size_t rlen, max_send_fragment; 917 918 if (!WPACKET_put_bytes_u8(thispkt, type)) { 919 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 920 ERR_R_INTERNAL_ERROR); 921 goto err; 922 } 923 SSL3_RECORD_add_length(thiswr, 1); 924 925 /* Add TLS1.3 padding */ 926 max_send_fragment = ssl_get_max_send_fragment(s); 927 rlen = SSL3_RECORD_get_length(thiswr); 928 if (rlen < max_send_fragment) { 929 size_t padding = 0; 930 size_t max_padding = max_send_fragment - rlen; 931 if (s->record_padding_cb != NULL) { 932 padding = s->record_padding_cb(s, type, rlen, s->record_padding_arg); 933 } else if (s->block_padding > 0) { 934 size_t mask = s->block_padding - 1; 935 size_t remainder; 936 937 /* optimize for power of 2 */ 938 if ((s->block_padding & mask) == 0) 939 remainder = rlen & mask; 940 else 941 remainder = rlen % s->block_padding; 942 /* don't want to add a block of padding if we don't have to */ 943 if (remainder == 0) 944 padding = 0; 945 else 946 padding = s->block_padding - remainder; 947 } 948 if (padding > 0) { 949 /* do not allow the record to exceed max plaintext length */ 950 if (padding > max_padding) 951 padding = max_padding; 952 if (!WPACKET_memset(thispkt, 0, padding)) { 953 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 954 ERR_R_INTERNAL_ERROR); 955 goto err; 956 } 957 SSL3_RECORD_add_length(thiswr, padding); 958 } 959 } 960 } 961 962 /* 963 * we should still have the output to thiswr->data and the input from 964 * wr->input. Length should be thiswr->length. thiswr->data still points 965 * in the wb->buf 966 */ 967 968 if (!SSL_WRITE_ETM(s) && mac_size != 0) { 969 unsigned char *mac; 970 971 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac) 972 || !s->method->ssl3_enc->mac(s, thiswr, mac, 1)) { 973 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 974 ERR_R_INTERNAL_ERROR); 975 goto err; 976 } 977 } 978 979 /* 980 * Reserve some bytes for any growth that may occur during encryption. 981 * This will be at most one cipher block or the tag length if using 982 * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case. 983 */ 984 if (!WPACKET_reserve_bytes(thispkt, SSL_RT_MAX_CIPHER_BLOCK_SIZE, 985 NULL) 986 /* 987 * We also need next the amount of bytes written to this 988 * sub-packet 989 */ 990 || !WPACKET_get_length(thispkt, &len)) { 991 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 992 ERR_R_INTERNAL_ERROR); 993 goto err; 994 } 995 996 /* Get a pointer to the start of this record excluding header */ 997 recordstart = WPACKET_get_curr(thispkt) - len; 998 999 SSL3_RECORD_set_data(thiswr, recordstart); 1000 SSL3_RECORD_reset_input(thiswr); 1001 SSL3_RECORD_set_length(thiswr, len); 1002 } 1003 1004 if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) { 1005 /* 1006 * We haven't actually negotiated the version yet, but we're trying to 1007 * send early data - so we need to use the tls13enc function. 1008 */ 1009 if (tls13_enc(s, wr, numpipes, 1) < 1) { 1010 if (!ossl_statem_in_error(s)) { 1011 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1012 ERR_R_INTERNAL_ERROR); 1013 } 1014 goto err; 1015 } 1016 } else { 1017 if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1) { 1018 if (!ossl_statem_in_error(s)) { 1019 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1020 ERR_R_INTERNAL_ERROR); 1021 } 1022 goto err; 1023 } 1024 } 1025 1026 for (j = 0; j < numpipes; j++) { 1027 size_t origlen; 1028 1029 thispkt = &pkt[j]; 1030 thiswr = &wr[j]; 1031 1032 /* Allocate bytes for the encryption overhead */ 1033 if (!WPACKET_get_length(thispkt, &origlen) 1034 /* Encryption should never shrink the data! */ 1035 || origlen > thiswr->length 1036 || (thiswr->length > origlen 1037 && !WPACKET_allocate_bytes(thispkt, 1038 thiswr->length - origlen, NULL))) { 1039 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1040 ERR_R_INTERNAL_ERROR); 1041 goto err; 1042 } 1043 if (SSL_WRITE_ETM(s) && mac_size != 0) { 1044 unsigned char *mac; 1045 1046 if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac) 1047 || !s->method->ssl3_enc->mac(s, thiswr, mac, 1)) { 1048 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1049 ERR_R_INTERNAL_ERROR); 1050 goto err; 1051 } 1052 SSL3_RECORD_add_length(thiswr, mac_size); 1053 } 1054 1055 if (!WPACKET_get_length(thispkt, &len) 1056 || !WPACKET_close(thispkt)) { 1057 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1058 ERR_R_INTERNAL_ERROR); 1059 goto err; 1060 } 1061 1062 if (s->msg_callback) { 1063 recordstart = WPACKET_get_curr(thispkt) - len 1064 - SSL3_RT_HEADER_LENGTH; 1065 s->msg_callback(1, 0, SSL3_RT_HEADER, recordstart, 1066 SSL3_RT_HEADER_LENGTH, s, 1067 s->msg_callback_arg); 1068 1069 if (SSL_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) { 1070 unsigned char ctype = type; 1071 1072 s->msg_callback(1, s->version, SSL3_RT_INNER_CONTENT_TYPE, 1073 &ctype, 1, s, s->msg_callback_arg); 1074 } 1075 } 1076 1077 if (!WPACKET_finish(thispkt)) { 1078 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1079 ERR_R_INTERNAL_ERROR); 1080 goto err; 1081 } 1082 1083 /* 1084 * we should now have thiswr->data pointing to the encrypted data, which 1085 * is thiswr->length long 1086 */ 1087 SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for 1088 * debugging */ 1089 SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH); 1090 1091 if (create_empty_fragment) { 1092 /* 1093 * we are in a recursive call; just return the length, don't write 1094 * out anything here 1095 */ 1096 if (j > 0) { 1097 /* We should never be pipelining an empty fragment!! */ 1098 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DO_SSL3_WRITE, 1099 ERR_R_INTERNAL_ERROR); 1100 goto err; 1101 } 1102 *written = SSL3_RECORD_get_length(thiswr); 1103 return 1; 1104 } 1105 1106 /* now let's set up wb */ 1107 SSL3_BUFFER_set_left(&s->rlayer.wbuf[j], 1108 prefix_len + SSL3_RECORD_get_length(thiswr)); 1109 } 1110 1111 /* 1112 * memorize arguments so that ssl3_write_pending can detect bad write 1113 * retries later 1114 */ 1115 s->rlayer.wpend_tot = totlen; 1116 s->rlayer.wpend_buf = buf; 1117 s->rlayer.wpend_type = type; 1118 s->rlayer.wpend_ret = totlen; 1119 1120 /* we now just need to write the buffer */ 1121 return ssl3_write_pending(s, type, buf, totlen, written); 1122 err: 1123 for (j = 0; j < wpinited; j++) 1124 WPACKET_cleanup(&pkt[j]); 1125 return -1; 1126 } 1127 1128 /* if s->s3->wbuf.left != 0, we need to call this 1129 * 1130 * Return values are as per SSL_write() 1131 */ 1132 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf, size_t len, 1133 size_t *written) 1134 { 1135 int i; 1136 SSL3_BUFFER *wb = s->rlayer.wbuf; 1137 size_t currbuf = 0; 1138 size_t tmpwrit = 0; 1139 1140 if ((s->rlayer.wpend_tot > len) 1141 || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) 1142 && (s->rlayer.wpend_buf != buf)) 1143 || (s->rlayer.wpend_type != type)) { 1144 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_WRITE_PENDING, 1145 SSL_R_BAD_WRITE_RETRY); 1146 return -1; 1147 } 1148 1149 for (;;) { 1150 /* Loop until we find a buffer we haven't written out yet */ 1151 if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0 1152 && currbuf < s->rlayer.numwpipes - 1) { 1153 currbuf++; 1154 continue; 1155 } 1156 clear_sys_error(); 1157 if (s->wbio != NULL) { 1158 s->rwstate = SSL_WRITING; 1159 /* TODO(size_t): Convert this call */ 1160 i = BIO_write(s->wbio, (char *) 1161 &(SSL3_BUFFER_get_buf(&wb[currbuf]) 1162 [SSL3_BUFFER_get_offset(&wb[currbuf])]), 1163 (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf])); 1164 if (i >= 0) 1165 tmpwrit = i; 1166 } else { 1167 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_WRITE_PENDING, 1168 SSL_R_BIO_NOT_SET); 1169 i = -1; 1170 } 1171 if (i > 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) { 1172 SSL3_BUFFER_set_left(&wb[currbuf], 0); 1173 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit); 1174 if (currbuf + 1 < s->rlayer.numwpipes) 1175 continue; 1176 s->rwstate = SSL_NOTHING; 1177 *written = s->rlayer.wpend_ret; 1178 return 1; 1179 } else if (i <= 0) { 1180 if (SSL_IS_DTLS(s)) { 1181 /* 1182 * For DTLS, just drop it. That's kind of the whole point in 1183 * using a datagram service 1184 */ 1185 SSL3_BUFFER_set_left(&wb[currbuf], 0); 1186 } 1187 return i; 1188 } 1189 SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit); 1190 SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit); 1191 } 1192 } 1193 1194 /*- 1195 * Return up to 'len' payload bytes received in 'type' records. 1196 * 'type' is one of the following: 1197 * 1198 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us) 1199 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us) 1200 * - 0 (during a shutdown, no data has to be returned) 1201 * 1202 * If we don't have stored data to work from, read a SSL/TLS record first 1203 * (possibly multiple records if we still don't have anything to return). 1204 * 1205 * This function must handle any surprises the peer may have for us, such as 1206 * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec 1207 * messages are treated as if they were handshake messages *if* the |recd_type| 1208 * argument is non NULL. 1209 * Also if record payloads contain fragments too small to process, we store 1210 * them until there is enough for the respective protocol (the record protocol 1211 * may use arbitrary fragmentation and even interleaving): 1212 * Change cipher spec protocol 1213 * just 1 byte needed, no need for keeping anything stored 1214 * Alert protocol 1215 * 2 bytes needed (AlertLevel, AlertDescription) 1216 * Handshake protocol 1217 * 4 bytes needed (HandshakeType, uint24 length) -- we just have 1218 * to detect unexpected Client Hello and Hello Request messages 1219 * here, anything else is handled by higher layers 1220 * Application data protocol 1221 * none of our business 1222 */ 1223 int ssl3_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf, 1224 size_t len, int peek, size_t *readbytes) 1225 { 1226 int i, j, ret; 1227 size_t n, curr_rec, num_recs, totalbytes; 1228 SSL3_RECORD *rr; 1229 SSL3_BUFFER *rbuf; 1230 void (*cb) (const SSL *ssl, int type2, int val) = NULL; 1231 int is_tls13 = SSL_IS_TLS13(s); 1232 1233 rbuf = &s->rlayer.rbuf; 1234 1235 if (!SSL3_BUFFER_is_initialised(rbuf)) { 1236 /* Not initialized yet */ 1237 if (!ssl3_setup_read_buffer(s)) { 1238 /* SSLfatal() already called */ 1239 return -1; 1240 } 1241 } 1242 1243 if ((type && (type != SSL3_RT_APPLICATION_DATA) 1244 && (type != SSL3_RT_HANDSHAKE)) || (peek 1245 && (type != 1246 SSL3_RT_APPLICATION_DATA))) { 1247 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_READ_BYTES, 1248 ERR_R_INTERNAL_ERROR); 1249 return -1; 1250 } 1251 1252 if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0)) 1253 /* (partially) satisfy request from storage */ 1254 { 1255 unsigned char *src = s->rlayer.handshake_fragment; 1256 unsigned char *dst = buf; 1257 unsigned int k; 1258 1259 /* peek == 0 */ 1260 n = 0; 1261 while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) { 1262 *dst++ = *src++; 1263 len--; 1264 s->rlayer.handshake_fragment_len--; 1265 n++; 1266 } 1267 /* move any remaining fragment bytes: */ 1268 for (k = 0; k < s->rlayer.handshake_fragment_len; k++) 1269 s->rlayer.handshake_fragment[k] = *src++; 1270 1271 if (recvd_type != NULL) 1272 *recvd_type = SSL3_RT_HANDSHAKE; 1273 1274 *readbytes = n; 1275 return 1; 1276 } 1277 1278 /* 1279 * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. 1280 */ 1281 1282 if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) { 1283 /* type == SSL3_RT_APPLICATION_DATA */ 1284 i = s->handshake_func(s); 1285 /* SSLfatal() already called */ 1286 if (i < 0) 1287 return i; 1288 if (i == 0) 1289 return -1; 1290 } 1291 start: 1292 s->rwstate = SSL_NOTHING; 1293 1294 /*- 1295 * For each record 'i' up to |num_recs] 1296 * rr[i].type - is the type of record 1297 * rr[i].data, - data 1298 * rr[i].off, - offset into 'data' for next read 1299 * rr[i].length, - number of bytes. 1300 */ 1301 rr = s->rlayer.rrec; 1302 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer); 1303 1304 do { 1305 /* get new records if necessary */ 1306 if (num_recs == 0) { 1307 ret = ssl3_get_record(s); 1308 if (ret <= 0) { 1309 /* SSLfatal() already called if appropriate */ 1310 return ret; 1311 } 1312 num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer); 1313 if (num_recs == 0) { 1314 /* Shouldn't happen */ 1315 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_READ_BYTES, 1316 ERR_R_INTERNAL_ERROR); 1317 return -1; 1318 } 1319 } 1320 /* Skip over any records we have already read */ 1321 for (curr_rec = 0; 1322 curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]); 1323 curr_rec++) ; 1324 if (curr_rec == num_recs) { 1325 RECORD_LAYER_set_numrpipes(&s->rlayer, 0); 1326 num_recs = 0; 1327 curr_rec = 0; 1328 } 1329 } while (num_recs == 0); 1330 rr = &rr[curr_rec]; 1331 1332 if (s->rlayer.handshake_fragment_len > 0 1333 && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE 1334 && SSL_IS_TLS13(s)) { 1335 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1336 SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA); 1337 return -1; 1338 } 1339 1340 /* 1341 * Reset the count of consecutive warning alerts if we've got a non-empty 1342 * record that isn't an alert. 1343 */ 1344 if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT 1345 && SSL3_RECORD_get_length(rr) != 0) 1346 s->rlayer.alert_count = 0; 1347 1348 /* we now have a packet which can be read and processed */ 1349 1350 if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, 1351 * reset by ssl3_get_finished */ 1352 && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) { 1353 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1354 SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); 1355 return -1; 1356 } 1357 1358 /* 1359 * If the other end has shut down, throw anything we read away (even in 1360 * 'peek' mode) 1361 */ 1362 if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { 1363 SSL3_RECORD_set_length(rr, 0); 1364 s->rwstate = SSL_NOTHING; 1365 return 0; 1366 } 1367 1368 if (type == SSL3_RECORD_get_type(rr) 1369 || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC 1370 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL 1371 && !is_tls13)) { 1372 /* 1373 * SSL3_RT_APPLICATION_DATA or 1374 * SSL3_RT_HANDSHAKE or 1375 * SSL3_RT_CHANGE_CIPHER_SPEC 1376 */ 1377 /* 1378 * make sure that we are not getting application data when we are 1379 * doing a handshake for the first time 1380 */ 1381 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && 1382 (s->enc_read_ctx == NULL)) { 1383 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1384 SSL_R_APP_DATA_IN_HANDSHAKE); 1385 return -1; 1386 } 1387 1388 if (type == SSL3_RT_HANDSHAKE 1389 && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC 1390 && s->rlayer.handshake_fragment_len > 0) { 1391 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1392 SSL_R_CCS_RECEIVED_EARLY); 1393 return -1; 1394 } 1395 1396 if (recvd_type != NULL) 1397 *recvd_type = SSL3_RECORD_get_type(rr); 1398 1399 if (len == 0) { 1400 /* 1401 * Mark a zero length record as read. This ensures multiple calls to 1402 * SSL_read() with a zero length buffer will eventually cause 1403 * SSL_pending() to report data as being available. 1404 */ 1405 if (SSL3_RECORD_get_length(rr) == 0) 1406 SSL3_RECORD_set_read(rr); 1407 return 0; 1408 } 1409 1410 totalbytes = 0; 1411 do { 1412 if (len - totalbytes > SSL3_RECORD_get_length(rr)) 1413 n = SSL3_RECORD_get_length(rr); 1414 else 1415 n = len - totalbytes; 1416 1417 memcpy(buf, &(rr->data[rr->off]), n); 1418 buf += n; 1419 if (peek) { 1420 /* Mark any zero length record as consumed CVE-2016-6305 */ 1421 if (SSL3_RECORD_get_length(rr) == 0) 1422 SSL3_RECORD_set_read(rr); 1423 } else { 1424 SSL3_RECORD_sub_length(rr, n); 1425 SSL3_RECORD_add_off(rr, n); 1426 if (SSL3_RECORD_get_length(rr) == 0) { 1427 s->rlayer.rstate = SSL_ST_READ_HEADER; 1428 SSL3_RECORD_set_off(rr, 0); 1429 SSL3_RECORD_set_read(rr); 1430 } 1431 } 1432 if (SSL3_RECORD_get_length(rr) == 0 1433 || (peek && n == SSL3_RECORD_get_length(rr))) { 1434 curr_rec++; 1435 rr++; 1436 } 1437 totalbytes += n; 1438 } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs 1439 && totalbytes < len); 1440 if (totalbytes == 0) { 1441 /* We must have read empty records. Get more data */ 1442 goto start; 1443 } 1444 if (!peek && curr_rec == num_recs 1445 && (s->mode & SSL_MODE_RELEASE_BUFFERS) 1446 && SSL3_BUFFER_get_left(rbuf) == 0) 1447 ssl3_release_read_buffer(s); 1448 *readbytes = totalbytes; 1449 return 1; 1450 } 1451 1452 /* 1453 * If we get here, then type != rr->type; if we have a handshake message, 1454 * then it was unexpected (Hello Request or Client Hello) or invalid (we 1455 * were actually expecting a CCS). 1456 */ 1457 1458 /* 1459 * Lets just double check that we've not got an SSLv2 record 1460 */ 1461 if (rr->rec_version == SSL2_VERSION) { 1462 /* 1463 * Should never happen. ssl3_get_record() should only give us an SSLv2 1464 * record back if this is the first packet and we are looking for an 1465 * initial ClientHello. Therefore |type| should always be equal to 1466 * |rr->type|. If not then something has gone horribly wrong 1467 */ 1468 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_READ_BYTES, 1469 ERR_R_INTERNAL_ERROR); 1470 return -1; 1471 } 1472 1473 if (s->method->version == TLS_ANY_VERSION 1474 && (s->server || rr->type != SSL3_RT_ALERT)) { 1475 /* 1476 * If we've got this far and still haven't decided on what version 1477 * we're using then this must be a client side alert we're dealing with 1478 * (we don't allow heartbeats yet). We shouldn't be receiving anything 1479 * other than a ClientHello if we are a server. 1480 */ 1481 s->version = rr->rec_version; 1482 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1483 SSL_R_UNEXPECTED_MESSAGE); 1484 return -1; 1485 } 1486 1487 /*- 1488 * s->rlayer.handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; 1489 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) 1490 */ 1491 1492 if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) { 1493 unsigned int alert_level, alert_descr; 1494 unsigned char *alert_bytes = SSL3_RECORD_get_data(rr) 1495 + SSL3_RECORD_get_off(rr); 1496 PACKET alert; 1497 1498 if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr)) 1499 || !PACKET_get_1(&alert, &alert_level) 1500 || !PACKET_get_1(&alert, &alert_descr) 1501 || PACKET_remaining(&alert) != 0) { 1502 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1503 SSL_R_INVALID_ALERT); 1504 return -1; 1505 } 1506 1507 if (s->msg_callback) 1508 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, s, 1509 s->msg_callback_arg); 1510 1511 if (s->info_callback != NULL) 1512 cb = s->info_callback; 1513 else if (s->ctx->info_callback != NULL) 1514 cb = s->ctx->info_callback; 1515 1516 if (cb != NULL) { 1517 j = (alert_level << 8) | alert_descr; 1518 cb(s, SSL_CB_READ_ALERT, j); 1519 } 1520 1521 if (alert_level == SSL3_AL_WARNING 1522 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) { 1523 s->s3->warn_alert = alert_descr; 1524 SSL3_RECORD_set_read(rr); 1525 1526 s->rlayer.alert_count++; 1527 if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) { 1528 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1529 SSL_R_TOO_MANY_WARN_ALERTS); 1530 return -1; 1531 } 1532 } 1533 1534 /* 1535 * Apart from close_notify the only other warning alert in TLSv1.3 1536 * is user_cancelled - which we just ignore. 1537 */ 1538 if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) { 1539 goto start; 1540 } else if (alert_descr == SSL_AD_CLOSE_NOTIFY 1541 && (is_tls13 || alert_level == SSL3_AL_WARNING)) { 1542 s->shutdown |= SSL_RECEIVED_SHUTDOWN; 1543 return 0; 1544 } else if (alert_level == SSL3_AL_FATAL || is_tls13) { 1545 char tmp[16]; 1546 1547 s->rwstate = SSL_NOTHING; 1548 s->s3->fatal_alert = alert_descr; 1549 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_READ_BYTES, 1550 SSL_AD_REASON_OFFSET + alert_descr); 1551 BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr); 1552 ERR_add_error_data(2, "SSL alert number ", tmp); 1553 s->shutdown |= SSL_RECEIVED_SHUTDOWN; 1554 SSL3_RECORD_set_read(rr); 1555 SSL_CTX_remove_session(s->session_ctx, s->session); 1556 return 0; 1557 } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) { 1558 /* 1559 * This is a warning but we receive it if we requested 1560 * renegotiation and the peer denied it. Terminate with a fatal 1561 * alert because if application tried to renegotiate it 1562 * presumably had a good reason and expects it to succeed. In 1563 * future we might have a renegotiation where we don't care if 1564 * the peer refused it where we carry on. 1565 */ 1566 SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_SSL3_READ_BYTES, 1567 SSL_R_NO_RENEGOTIATION); 1568 return -1; 1569 } else if (alert_level == SSL3_AL_WARNING) { 1570 /* We ignore any other warning alert in TLSv1.2 and below */ 1571 goto start; 1572 } 1573 1574 SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_SSL3_READ_BYTES, 1575 SSL_R_UNKNOWN_ALERT_TYPE); 1576 return -1; 1577 } 1578 1579 if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) { 1580 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) { 1581 BIO *rbio; 1582 1583 /* 1584 * We ignore any handshake messages sent to us unless they are 1585 * TLSv1.3 in which case we want to process them. For all other 1586 * handshake messages we can't do anything reasonable with them 1587 * because we are unable to write any response due to having already 1588 * sent close_notify. 1589 */ 1590 if (!SSL_IS_TLS13(s)) { 1591 SSL3_RECORD_set_length(rr, 0); 1592 SSL3_RECORD_set_read(rr); 1593 1594 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0) 1595 goto start; 1596 1597 s->rwstate = SSL_READING; 1598 rbio = SSL_get_rbio(s); 1599 BIO_clear_retry_flags(rbio); 1600 BIO_set_retry_read(rbio); 1601 return -1; 1602 } 1603 } else { 1604 /* 1605 * The peer is continuing to send application data, but we have 1606 * already sent close_notify. If this was expected we should have 1607 * been called via SSL_read() and this would have been handled 1608 * above. 1609 * No alert sent because we already sent close_notify 1610 */ 1611 SSL3_RECORD_set_length(rr, 0); 1612 SSL3_RECORD_set_read(rr); 1613 SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_READ_BYTES, 1614 SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY); 1615 return -1; 1616 } 1617 } 1618 1619 /* 1620 * For handshake data we have 'fragment' storage, so fill that so that we 1621 * can process the header at a fixed place. This is done after the 1622 * "SHUTDOWN" code above to avoid filling the fragment storage with data 1623 * that we're just going to discard. 1624 */ 1625 if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) { 1626 size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment); 1627 unsigned char *dest = s->rlayer.handshake_fragment; 1628 size_t *dest_len = &s->rlayer.handshake_fragment_len; 1629 1630 n = dest_maxlen - *dest_len; /* available space in 'dest' */ 1631 if (SSL3_RECORD_get_length(rr) < n) 1632 n = SSL3_RECORD_get_length(rr); /* available bytes */ 1633 1634 /* now move 'n' bytes: */ 1635 memcpy(dest + *dest_len, 1636 SSL3_RECORD_get_data(rr) + SSL3_RECORD_get_off(rr), n); 1637 SSL3_RECORD_add_off(rr, n); 1638 SSL3_RECORD_sub_length(rr, n); 1639 *dest_len += n; 1640 if (SSL3_RECORD_get_length(rr) == 0) 1641 SSL3_RECORD_set_read(rr); 1642 1643 if (*dest_len < dest_maxlen) 1644 goto start; /* fragment was too small */ 1645 } 1646 1647 if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) { 1648 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1649 SSL_R_CCS_RECEIVED_EARLY); 1650 return -1; 1651 } 1652 1653 /* 1654 * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or 1655 * protocol violation) 1656 */ 1657 if ((s->rlayer.handshake_fragment_len >= 4) 1658 && !ossl_statem_get_in_handshake(s)) { 1659 int ined = (s->early_data_state == SSL_EARLY_DATA_READING); 1660 1661 /* We found handshake data, so we're going back into init */ 1662 ossl_statem_set_in_init(s, 1); 1663 1664 i = s->handshake_func(s); 1665 /* SSLfatal() already called if appropriate */ 1666 if (i < 0) 1667 return i; 1668 if (i == 0) { 1669 return -1; 1670 } 1671 1672 /* 1673 * If we were actually trying to read early data and we found a 1674 * handshake message, then we don't want to continue to try and read 1675 * the application data any more. It won't be "early" now. 1676 */ 1677 if (ined) 1678 return -1; 1679 1680 if (!(s->mode & SSL_MODE_AUTO_RETRY)) { 1681 if (SSL3_BUFFER_get_left(rbuf) == 0) { 1682 /* no read-ahead left? */ 1683 BIO *bio; 1684 /* 1685 * In the case where we try to read application data, but we 1686 * trigger an SSL handshake, we return -1 with the retry 1687 * option set. Otherwise renegotiation may cause nasty 1688 * problems in the blocking world 1689 */ 1690 s->rwstate = SSL_READING; 1691 bio = SSL_get_rbio(s); 1692 BIO_clear_retry_flags(bio); 1693 BIO_set_retry_read(bio); 1694 return -1; 1695 } 1696 } 1697 goto start; 1698 } 1699 1700 switch (SSL3_RECORD_get_type(rr)) { 1701 default: 1702 /* 1703 * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but 1704 * TLS 1.2 says you MUST send an unexpected message alert. We use the 1705 * TLS 1.2 behaviour for all protocol versions to prevent issues where 1706 * no progress is being made and the peer continually sends unrecognised 1707 * record types, using up resources processing them. 1708 */ 1709 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1710 SSL_R_UNEXPECTED_RECORD); 1711 return -1; 1712 case SSL3_RT_CHANGE_CIPHER_SPEC: 1713 case SSL3_RT_ALERT: 1714 case SSL3_RT_HANDSHAKE: 1715 /* 1716 * we already handled all of these, with the possible exception of 1717 * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but 1718 * that should not happen when type != rr->type 1719 */ 1720 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1721 ERR_R_INTERNAL_ERROR); 1722 return -1; 1723 case SSL3_RT_APPLICATION_DATA: 1724 /* 1725 * At this point, we were expecting handshake data, but have 1726 * application data. If the library was running inside ssl3_read() 1727 * (i.e. in_read_app_data is set) and it makes sense to read 1728 * application data at this point (session renegotiation not yet 1729 * started), we will indulge it. 1730 */ 1731 if (ossl_statem_app_data_allowed(s)) { 1732 s->s3->in_read_app_data = 2; 1733 return -1; 1734 } else if (ossl_statem_skip_early_data(s)) { 1735 /* 1736 * This can happen after a client sends a CH followed by early_data, 1737 * but the server responds with a HelloRetryRequest. The server 1738 * reads the next record from the client expecting to find a 1739 * plaintext ClientHello but gets a record which appears to be 1740 * application data. The trial decrypt "works" because null 1741 * decryption was applied. We just skip it and move on to the next 1742 * record. 1743 */ 1744 if (!early_data_count_ok(s, rr->length, 1745 EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) { 1746 /* SSLfatal() already called */ 1747 return -1; 1748 } 1749 SSL3_RECORD_set_read(rr); 1750 goto start; 1751 } else { 1752 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_READ_BYTES, 1753 SSL_R_UNEXPECTED_RECORD); 1754 return -1; 1755 } 1756 } 1757 } 1758 1759 void ssl3_record_sequence_update(unsigned char *seq) 1760 { 1761 int i; 1762 1763 for (i = 7; i >= 0; i--) { 1764 ++seq[i]; 1765 if (seq[i] != 0) 1766 break; 1767 } 1768 } 1769 1770 /* 1771 * Returns true if the current rrec was sent in SSLv2 backwards compatible 1772 * format and false otherwise. 1773 */ 1774 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl) 1775 { 1776 return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]); 1777 } 1778 1779 /* 1780 * Returns the length in bytes of the current rrec 1781 */ 1782 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl) 1783 { 1784 return SSL3_RECORD_get_length(&rl->rrec[0]); 1785 } 1786